Wednesday, February 15, 2012

Dynamic SQL H_ll Please Help Again

Still need help !

Can ANYONE tell me why this does not work ??

********
This Works when hard coded
DECLARE @.RtnValue smallint
SET @.RtnValue = 0

SELECT @.RtnValue = (SELECT MyColumn0 FROM MyTable WHERE RowIndex = 700)
********

????
This DOES NOT Work
DECLARE @.RtnValue smallint
SET @.RtnValue = 0

DECLARE @.MySelectString varchar(200)
SET @.MySelectString = 'SELECT @.RtnValue = ( SELECT MyColumn0 FROM MyTable WHERE RowIndex = 700)'
PRINT @.MySelectString

EXEC ( @.MySelectString )
????

!!!!!!!!
This is the error message when I run in SQL Query Analyzer
SELECT @.RtnValue = ( SELECT MyColumn0 FROM MyTable WHERE RowIndex = 700)
Server: Msg 137, Level 15, State 1, Line 1
Must declare the variable'@.RtnValue'.
!!!!!!!!!

I PRINT the @.MySelectString to varify and it look correct but when used in the EXEC() it does not work

Please help !

check out Books online about using sp_Executesql.
|||I too faced the similar issue, then I used a temporary table to insert the selected value of dynamic query and assigned it to the variable...though it is not a better approach..no other go as of now..!!!!|||To expand on what Dinakar said, check outthis code snippetfrom Nigel Rivett which shows how to set a variable from dynamicSQL. You need to use sp_executesql with an output parameter.
There is also a KB article on this topic which explains the concept in further detail:INF: Using Output Parameters with sp_executesql

No comments:

Post a Comment