SQL Server - 查找具有唯一ID值的数据库中的所有表

时间:2014-10-17 14:50:12

标签: sql-server database

大家好,我想知道你是否可以帮助我。

我想找出数据库中的所有表(在SQLServer中),其中列IDName具有特定值' SAM',就像IDName =' SAM'。所以我最初的apporach是创建一个表,其中包含列" IDName" (因为并非数据库中的所有表都有此列。然后我想通过每个表来查看哪些表与IDName匹配=' SAM' - 这就是我被困的地方。我和#39;我很确定有更快的方法可以做到这一点,但我不太熟悉数据库查询编码。任何事情都会有所帮助谢谢!

select * into tmp from
(
SELECT SO.NAME AS TableName, SC.NAME AS ColumnName
FROM dbo.sysobjects SO INNER JOIN dbo.syscolumns SC ON SO.id = SC.id 
WHERE sc.name = 'IDName'   and SO.type = 'U'
) tablelist

所以,如果我去"从tmp"中选择*我得到的列表包含#34; IDName"现在我必须浏览每个列表,看看他们是否有" IDName =' Sam'"如果他们确实将它添加到输出表。最后,我希望看到数据库中具有IDName' Sam'的所有表名。

1 个答案:

答案 0 :(得分:2)

DECLARE @sql AS varchar(max) = '';
DECLARE @ColumnName AS varchar(100) = 'IDName'
DECLARE @ResultQuery AS varchar(max) =  'SELECT ''@TableName'' AS TableName ' + 
                                        '       ,@ColumnName ' +
                                        'FROM @TableName ' +
                                        'WHERE @ColumnName = ''SAM''';
SET @ResultQuery = REPLACE(@ResultQuery, '@ColumnName', QUOTENAME(@ColumnName));

WITH AllTables AS (
    SELECT SCHEMA_NAME(Tables.schema_id) AS SchemaName
          ,Tables.name AS TableName
          ,Columns.name AS ColumnName
    FROM sys.tables AS Tables
        INNER JOIN sys.columns AS Columns 
            ON Tables.object_id = Columns.object_id
    WHERE Columns.name = @ColumnName
)
SELECT @sql = @sql + ' UNION ALL ' +
       REPLACE(@ResultQuery, '@TableName', QUOTENAME(TableName)) + CHAR(13)
FROM AllTables

SET @sql = STUFF(@sql, 1, LEN(' UNION ALL'), '');

--PRINT @sql;

SET @sql = 
'WITH AllTables AS ( ' +
   @sql + 
') ' +
'SELECT DISTINCT TableName ' +
'FROM AllTables ';

EXEC (@sql)