列中包含特定数据的所有表的列表

时间:2017-06-20 12:13:54

标签: sql sql-server tsql

使用此查询,我获得包含名为“Status_ID”

列的所有表
SELECT
   c.name AS 'ColumnName'
  ,t.name AS 'TableName'
FROM sys.columns c
   JOIN sys.tables  t ON c.object_id = t.object_id
WHERE c.name LIKE 'Status_ID'

Status_ID中的数据可能只有1到6的值。 我想要的是获取所有表的列表,其中Status_ID = 2 至少一次。 (从上面的代码中排除所有不包含Status_ID = 2数据的表)

2 个答案:

答案 0 :(得分:0)

Solution 1: Run the below query, which will give you a select query with all the tables containing status_id column. then copy and execute the select query to find the data.

SELECT 'select *  from ' + TABLE_NAME + '  where Status_ID = ''2'''
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'Status_ID'

Solution 2: You may need to use the following solution to find the data in all tables Find a string by searching all tables in SQL Server Management Studio 2008

答案 1 :(得分:0)

This should do the trick:

DECLARE @sql NVARCHAR(MAX) = 'DECLARE @tables NVARCHAR(MAX) = '''' ;' ;
DECLARE @tables NVARCHAR(MAX) = '';
SELECT   @SQL += 'IF EXISTS (SELECT ''X''  FROM ' + QUOTENAME(t.name)
         + 'WHERE STATUS_ID =2) SET @tables+= ' + '''' + + ',' + 
QUOTENAME(t.name) + ''''
         + ';'
FROM     sys.columns c
         JOIN sys.tables t ON c.object_id = t.object_id
WHERE    c.name LIKE 'STATUS_ID'


SET @sql += 'SELECT SUBSTRING(@TABLES,2,LEN(@TABLES));'
EXEC(@SQL);