1

How to get output from exec (using strings) and assign it to a local variable?

Code:

declare @qry nvarchar(500)
declare @StateId nvarchar(10) 

set @qry= 'Select top 1 StateId FROM '+@TableName+' where '+@ColumnName+'='+str(@BusinessId)
exec(@qry)

I want

@StateID = exec(@qry)
1

2 Answers 2

3
declare @qry nvarchar(max) = 'select @id = id from ts_trails where id = 500'
declare @id nvarchaR(500)

exec sp_executesql @qry, N'@id int out', @id out

select @id

USE sp_executesql then make your variable the output parameter

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

Comments

0

If you want only one record:

 Declare @id int;
 select @id= column_id from yourtable
 select @id

This is passing data to variable

1 Comment

Then you can change from int to varchar

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.