- Copy the code into a new query window.
- Edit the SET @Object variable as required.
- Execute the script.
Simples
nbhatt,
2013-07-30 (first published: 2013-06-12)
Simples
DECLARE @Cursor CURSOR DECLARE @DatabaseName VARCHAR(100) DECLARE @Object VARCHAR(100) DECLARE @Message VARCHAR(100) --Enter object you are trying to find: SET @Object = 'YourTableName' SET @Message = 'Object found in database: ' SET @Cursor = CURSOR FOR SELECT name FROM sys.databases WHERE [state] = 0 --0 = Online OPEN @Cursor FETCH NEXT FROM @Cursor INTO @DatabaseName WHILE (@@FETCH_STATUS = 0) BEGIN DECLARE @SQL VARCHAR(MAX) SET @SQL = ' IF (SELECT COUNT(0) FROM [' + @DatabaseName + '].sys.objects WHERE name = ''' + @Object + ''') > 0 BEGIN PRINT ''' + @Message + @DatabaseName + ''' END ' --PRINT @SQL EXEC (@SQL) FETCH NEXT FROM @Cursor INTO @DatabaseName END CLOSE @Cursor DEALLOCATE @Cursor
Based on a real fact, this article demonstrates how a bad use of sp_executesql can lead to unpleasant surprises
Dynamic SQL is essentially normal SQL written in such a way that you end up with a “customised” SQL script at run-time.
This example demonstrates how to perform a pivot using dynamic headers based on the row values of a table. The article also shows how to pass a temp table variable to a Dynamic SQL call.
2017-08-04 (first published: 2015-10-22)
11,921 reads
This article by Jonathan Roberts demonstrates how to use dynamic SQL and overcome its downsides.
2012-02-17 (first published: 2010-05-20)
30,329 reads
When you have too many tables in a view, what can you do? New author Henrik Staun Poulsen brings us a solution that we