Monday, July 14, 2008

 

Assigning values to T-SQL varaibles using Dynamic Queries

Although not recommended for security reasons, Dynamic SQL can prove to be quite handy when it comes to customizing queries to run on multilple tables/databases. There are certain situations when using Dynamic SQL is the better option, at the same time being reasonably safe. I ran into one such situation when I used it during a backend process of transferring records from one database to another, with the user completely oblivious to the whole thing.

Anyway, I ran into a little obstacle when I needed to assign the result of a query being run using dynamic sql to a local variable of a stored procedure. Here's how I resolved it:

-- Declare a variable to hold our sql statement
Declare @sql nvarchar(max)

-- Declare the variable that should store the result
Declare @vcTemp varchar(max)

-- Do a select on a table, basically write any query you want as long as
-- it uses our variable

Select @sql = N'Select top 1 @vcTemp = from '

-- Call the built-in sp_executesql SP specifying our varibale as the
-- output
EXEC sp_executesql @sql, N'@vcTemp varchar(max) output', @vcTemp output

-- Doing a simple select will reveal, the value has been read into it

Select @vcTemp


It was a cool new thing I learned, so I thought I'd share. Hope this helped.

Comments:
I've been finding this answer about 3 hours and you helps me a lot. Thank you very much for sharing.
best regards,
 
wow man... Most of the stuff that you wrote went over my head. Even though i hate to admit it, i'm a complete dumbass when it comes to tech related stuff. O well... This is your style, you like it and that's what's important :-)
Cheers
 
@antivirux
You're most welcome.

@YH
Well, you're not expected to understand this unless you're a software engineer and have worked/studied Databases at some point.
 

Post a Comment



<< Home