Dynamic USE statement

If you have tried to excute dynamic SQL on multiple databases at once then you have probably had problems with the USE statement. Here is how I worked around it. You can use the sp_executesql stored procedure and provide it database context like below.


DECLARE @sql VARCHAR(MAX)
SET @sql = 'YOUR AWESOME SQL STATEMENT HERE';
EXEC(@dbname + '..sp_executesql N''' + @sql + '''');

The trickiest part of this solution for me was handling the quotes in the EXEC statement. You can play around with the command by using the PRINT statement to work on the command.


DECLARE @sql VARCHAR(MAX)
SET @sql = 'YOUR AWESOME SQL STATEMENT HERE';
PRINT(@dbname + '..sp_executesql N''' + @sql + '''');
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s