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