I have a table that exists on a linked server and it has a field called name and I want to search a string called Macy’s on that field. I am executing this as a dynamic SQL:-
declare @Sql nvarchar(2000)
declare @searchName nvarchar(255)
SET @searchName = N'macy''s'
SET @sql = 'SELECT * from crm_opportunity o where o.NAME LIKE ''% ' + @searchName + '%'' ESCAPE '''''' '
exec (@sql).
In other words I am trying to escape the single quote. I get the error Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ‘s’.
Any ideas and suggestions!
Instead of using
EXEC, usesp_executesqland parameterize your query:Not only does this help avoid confusing quote escaping, but it also protects you against Sql Injection attacks.