2

Possible Duplicate:
Assign result of dynamic sql to variable

Can you help me to store a value in the given example.

DECLARE @variable VARCHAR(20)

declare @table_name varchar(20)='sample_table'

EXEC('SELECT '+@variable+'=SUM(CAST([Annual Plan & GM$] AS MONEY)) FROM '+@table_name+'')
1
  • So what is the problem you are getting with the above query? You might want to declare another var called '@SQL', and build the query in that variable. Then you can use EXEC '@SQL'. Commented Jan 18, 2013 at 12:32

1 Answer 1

3

You can return a typed output parameter using sp_executesql:

declare @variable   money
declare @table_name varchar(20)='sample_table'

declare @sql nvarchar(255) = 'SELECT @variable=SUM(CAST([Annual Plan & GM$] AS MONEY)) FROM '+ @table_name
EXEC sp_executesql @sql, 
    N'@variable money OUTPUT',
    @variable OUTPUT

select @variable
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Alex Yah! got the result...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.