-1

I'm facing a very strange behavior of a like search within a sp_executesql:

This statement returns 0 rows:

exec sp_executesql N'SELECT * FROM MyTable WHERE Name LIKE ''%'' +
     @Name + ''%''',N'@Name nvarchar(7)',@Name=N'100024​'

When this equivalent returns the desired row:

DECLARE @Name nvarchar(7)=N'100024'    
SELECT * FROM MyTable WHERE Name LIKE '%' + @Name + '%'

What's wrong with exec sp_executesql command? if I use it to search other row such as "100033" it finds the row, so syntax must be fine (in fact the query was taken from SQL Profiler when trying to debug why my asp.net page didn't found this particular element)

David Walschots
  • 12,279
  • 5
  • 36
  • 59
user1416197
  • 155
  • 1
  • 7

3 Answers3

3

You have an invisible symbol here @Name=N'100024​'

enter image description here

Andrey Morozov
  • 7,839
  • 5
  • 53
  • 75
0

You have strange unicode characters in the N'100024​' part. Try delete the part N'100024​' and write it anew.

Example - first line works ok, second line does not work:

exec sp_executesql N'SELECT * FROM #MyTable WHERE Name LIKE ''%''+@Name+''%''', N'@Name nvarchar(200)',@Name=N'100024'
exec sp_executesql N'SELECT * FROM #MyTable WHERE Name LIKE ''%''+@Name+''%''', N'@Name nvarchar(200)',@Name=N'100024​'

Try to save the query in SQL management studio and then open it in you will see characters like: @Name=N'100024‚Äč'. It will prompt you if you want to save in unicode.

Vojtěch Dohnal
  • 7,867
  • 3
  • 43
  • 105
0

You seem to be have an incorrect number of single quotes ('). This (copied from your sp_execute bit):

DECLARE @Name nvarchar(7);
SET @Name = '100024​'
PRINT 'SELECT * FROM MyTable WHERE Name LIKE ''%'' +      @Name + ''%'''

outputs this:

SELECT * FROM MyTable WHERE Name LIKE '%' +      @Name + '%'

Try removing a single quote prior and after the @name:

'SELECT * FROM MyTable WHERE Name LIKE ''%' +      @Name + '%'''

Output:

SELECT * FROM MyTable WHERE Name LIKE '%100024?%'
SchmitzIT
  • 9,227
  • 9
  • 65
  • 92