Using LIKE in sp_executesql

SET @whereCond = @whereCond + 'And LIKE name' '%' '+ @name +' '%' ''

Something is wrong? After I create the condition, I execute it with sp_executesql, but I got something. When I select the same without sp, this is normal.

How to use LIKE in sp_executesql? Can you give some examples, please?

Thank.

UPDATE

declare @name nvarchar(50)

set @name = 'a'

SELECT *
    FROM Tbl_Persons WHERE 1 = 1  AND lastname LIKE '%a%' 

exec sp_executesql 
  N'SELECT *
    FROM Tbl_Persons WHERE 1 = 1  AND lastname LIKE ''%@name%''', 
  N'@name nvarchar(50)',
  @name=@name

The first query returns values, the second returns nothing.

Who cares?

+5
source share
1 answer

Following work for me

declare @name varchar(50)

set @name = 'WAITFOR'


exec sp_executesql 
  N'select * from sys.messages WHERE text  LIKE ''%'' + @name + ''%''', 
  N'@name varchar(50)',
  @name=@name

I think the problem should be elsewhere.

Edit: After updating you should use

exec sp_executesql 
  N'SET @name = ''%'' + @name + ''%'';
    SELECT *
    FROM Tbl_Persons WHERE 1 = 1  AND lastname LIKE @name', 
  N'@name nvarchar(50)',
  @name=@name

, @name

+14

All Articles