9

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

Is there something wrong here? After I generate where condition, I execute it with sp_executesql, but I did get anything. When I SELECT the same thing without sp, it's ok.

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

Thank you.

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

First query returns values, second one doesn't return anything.

What's the difference?

hgulyan
  • 8,099
  • 8
  • 50
  • 75

1 Answers1

19

The following works 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 must lie elsewhere.

Edit: Following your update you need to 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

As it stands you are searching for text containing the actual substring @name

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
  • I've checked your script and it's working, but mine doesn't work. I've edited my question. thank you. – hgulyan Aug 24 '10 at 13:02
  • why is this assignment '@name=@name' required here, Isn't just enough to pass @name ? – IKriKan Feb 06 '19 at 15:29
  • 1
    @IKriKan The first name is the parameter used in the query expression and the second name is the variable containing the value (that should substitute the parameter). I prefer to give them different names though. – Gerhard Liebenberg Aug 18 '20 at 13:20
  • This doesn't work when @name contains apostrophe character (single quotation mark) , for example D'souza – PalakM Jul 27 '21 at 08:30
  • @PalakM - yes it does. This isn't creating the SQL string itself with concatenation – Martin Smith Jul 27 '21 at 08:32
  • 1
    See for example `declare @name varchar(50) set @name = 'it''s' exec sp_executesql N'select * from sys.messages WHERE text LIKE ''%'' + @name + ''%''', N'@name varchar(50)', @name=@name` which returns these results https://i.stack.imgur.com/l8XRv.png – Martin Smith Jul 27 '21 at 08:34
  • I was missing escape character. thank you – PalakM Jul 27 '21 at 09:17