Friday, March 30, 2012

Question about sp_executesql

Hi all,
I just wanted to know why this doesn't work: if @.1's values is computer
--------------------------------
BEGIN
FETCH NEXT FROM keyword_cursor into @.1

SELECT @.sql = @.sql + 'where title LIKE ' +'''%@.x1%''' + ' OR notes like ' +'''%@.x1%'''

SELECT @.paramlist ='@.x1 nvarchar(200)'
print @.sql
EXEC sp_executesql @.sql, @.paramlist, @.1

RETURN 0
END
The @.sql string evaluates to:
select title, notes from pubs..titles where title LIKE'%@.x1%' OR notes like'%@.x1%'
--------------------------------
But this works:
BEGIN
FETCH NEXT FROM keyword_cursor into @.1

SELECT @.sql = @.sql + 'where title LIKE ''%''+ @.x1 + ''%'' OR notes like ''%'' + @.x1 + ''%'''

SELECT @.paramlist ='@.x1 nvarchar(200)'
print @.sql
EXEC sp_executesql @.sql, @.paramlist, @.1

RETURN 0
END
The @.sql string evaluates to:
select title, notes from pubs..titles where title LIKE '%'+ @.x1 + '%' OR notes like '%' + @.x1 + '%'
----------------------------------
I just don't get it ?? Doesn't sp_executesql just replaces the @.x1 with @.1?

I don't believe so. It will execute the exact string you passed in.
select title, notes from pubs..titles where title LIKE'%@.x1%' OR notes like'%@.x1%'
look at that for instance. If you ran that in query analyzer, itwould not replace '%@.x1%' with anything because it's infact in thestring. @.x1 should be treated as a variable, and must be outsideof any string delimiter such as '.
Another example just in case is..
Dim strName as String = "KraGiE"
Response.Write("hello strName")
That would not replace strName with "KraGiE" because it's not being used as a variable.
|||Hi KraGie,
Thanks for your reply and explaination. Now i understand why the string "select title, notes from pubs..titles where title LIKE'%@.x1%' OR notes like'%@.x1%'". But i still don't get why the second string "select title, notes from pubs..titles where title LIKE'%' + @.x1 + '%' OR notes like'%' + @.x1 + '%'" will work. Because after the replacement of the variable @.x1 with "computer" then it will evaluate to select title, notes from pubs..titles where title LIKE %computer% OR notes like %computer% right? without the single quotes outside the percentage signs won't the statement generate an error??

No comments:

Post a Comment