SQL查询以查找数据库中特定列的所有引用?

时间:2017-11-20 20:21:38

标签: sql sql-server

我需要编写一些SQL来查找数据库中特定列的所有引用。我尝试查找引用的列存在于不同的数据库中。我找到了一些查找相同数据库中列的引用的示例:

In SQL Server, how can I find everywhere a column is referenced?

但我在查找如何为不同数据库中存在的列执行此操作时遇到问题。你能为此提供SQL吗?例如,让我们参考我试图找到的外部列:

MyExternalDB.MyExternalSchema.MyExternalTable.MyExternalColumn

1 个答案:

答案 0 :(得分:0)

好的,只需运行此命令并确保设置ColumnName变量

USE [master];
GO

IF OBJECT_ID('tempdb..#columns') IS NOT NULL
    DROP TABLE #columns;
GO


CREATE TABLE #columns
    ( databaseName nvarchar(MAX),
      columnid     int,
      columnName   nvarchar(MAX),
      objectid     int,
      objectName   nvarchar(MAX));

DECLARE @databaseName sysname;
DECLARE @columnName nvarchar(MAX) = 'ColumnName';

DECLARE cur CURSOR LOCAL FORWARD_ONLY STATIC FOR
    SELECT [name]
    FROM [sys].[databases]
    WHERE [state] = 0
      AND [name] NOT IN ( 'tempdb', 'master', 'msdb', 'model' );
OPEN cur;
FETCH NEXT FROM cur
INTO @databaseName;
WHILE ( @@FETCH_STATUS != -1 )
    BEGIN;
        IF ( @@FETCH_STATUS != -2 )
            BEGIN;

                DECLARE @statement nvarchar(MAX);

                SET @statement =N'Use '+ @databaseName +
                N';
                if EXISTS (SELECT name FROM sys.[columns] WHERE name = ''' + @columnName + ''')
                BEGIN;
                INSERT [#columns] ( [databaseName], [columnid], [columnName], [objectid], [objectName] )
                       SELECT ''' + @databaseName + N''',
                              c.[column_id],
                              c.[name],
                              o.[object_id],
                              o.[name]
                       FROM sys.[columns] c
                       INNER JOIN sys.[objects] o
                          ON [o].[object_id] = [c].[object_id]
                       WHERE c.[name] = ''' + @columnName + '''; 
                       END;';

                EXEC [sys].[sp_executesql] @stmt = @statement;


            END;
        FETCH NEXT FROM cur
        INTO @databaseName;
    END;
CLOSE cur;
DEALLOCATE cur;

SELECT * FROM [#columns];