It seems that using LIKE in a wildcard condition and variable inside dynamic sql does not work, although it does not give an error. Here is an example.
The code column has values such as A0B01C02, A0B02C2D05, A0B02C2D05, etc., and I'm trying to match rows containing a subset of type "B1". When I do this, it works and returns the results as expected.
set @sql='select * from table where code like ''%B01%'''
exec sp_executesql @sql
If I rigidly set the value of the set @code = 'B01' variable and change the sql operator to concatenate quotes and wildcards:
set @sql='select * from table where code like ' +''''+ '%'+@code + '%' + ''''
exec sp_executesql @sql
This returns the results as expected, but I had to hard code the variable. However, when I need to make a match using a variable for B01 and that the variable is set using the select statement, I get no results. I define nvarchar as follows:
set @code=(select top 1 code from anotherTable where USERID=@PersonId)
I confirmed that the above select statement returns the expected code. There is no error, but the request is successful. Am I missing something in the syntax for the where clause?
source
share