2

I have an issue with a my SQL query. I need to execute a SQL statement using EXEC and one of the columns is already represented with a variable and I must now put the represent the value of that column with another variable. Can this be achieved and if so, can you please suggest any other solution for this?

I found this snippet via Google. But even this doesn't give me the desired output.

My SQL Statement:

declare @i int, @j int =10
exec sp_executesql N'select @i ='+ @j, N'@i int output', @i output
select @i

1 Answer 1

3

This works in my Sql Server 2005:

    declare @i int, @j int
    set @j =10
    declare @sql nvarchar(max)
    set @sql = 'select @i =' + str(@j)
    exec sp_executesql @sql, N'@i int output', @i output
    select @i
3
  • thnx it works.. can i know what is that difference? oh.. other than the casting problem..
    – itb564
    Apr 5, 2012 at 12:32
  • Casting, then you cannot initialize variable at the declaration, and sp_execute_sql does not accept expression as parameter. You have to send a variable, @sql in this case. Apr 5, 2012 at 12:37
  • SQL server 2008 and above can initialize variables in their declarations. Apr 5, 2012 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.