如何检索一组具有特定值的表名?

时间:2013-08-17 00:40:50

标签: sql-server

例如,我的数据库中有100个表(table1,table2,table3,table4和table5 .....),table1中的coloumns col1,col2 ... col7就像每个表都有一些列一样明智。列col7的值为“BOLD”。在这里,我想检索保持值'BOLD'的表。

2 个答案:

答案 0 :(得分:0)

也许这个question有你想要的东西。

从接受的答案中取出的脚本:

SELECT 'SELECT * FROM [' + tables.TABLE_NAME + '] WHERE ['
       + Columns.Column_Name + '] = ' + CONVERT(varchar(50),@COLUMNVALUE)
FROM INFORMATION_SCHEMA.Columns as Columns
INNER JOIN INFORMATION_SCHEMA.TABLES as tables 
    On Columns.TABLE_NAME = tables.TABLE_NAME
WHERE Columns.DATA_TYPE = @COLUMNTYPE

答案 1 :(得分:0)

根据Felipe的回答,您可以使用生成的SELECT,并在一个循环中执行它们:

SELECT 'SELECT TOP 1 1 FROM [' + tables.TABLE_NAME + '] WHERE [' + Columns.Column_Name + '] LIKE ''%' + CONVERT(varchar(50),'BOLD') + '%''' As Qry, 
    IDENTITY(int,1,1) As Id,
    tables.TABLE_NAME As TableName,
    Cast(null As Bit) As ContainsText
INTO #Queries
FROM INFORMATION_SCHEMA.Columns as Columns
INNER JOIN INFORMATION_SCHEMA.TABLES as tables 
    On Columns.TABLE_NAME = tables.TABLE_NAME
WHERE Columns.DATA_TYPE in ('varchar','nvarchar','text')

DECLARE @TableName NVARCHAR(MAX), @Qry NVARCHAR(MAX), @ContainsText BIT, @id INT
WHILE EXISTS (SELECT * FROM #Queries WHERE ContainsText IS NULL)
BEGIN
    SELECT TOP 1 @id = id, @TableName = TableName, @Qry = Qry FROM #Queries WHERE ContainsText IS NULL
    EXEC (@Qry)
    If (@@ROWCOUNT > 0)
        Set @ContainsText = 1
    Else
        Set @ContainsText = 0
    UPDATE #Queries SET ContainsText = @ContainsText WHERE id = @id
END

SELECT * FROM #Queries Where ContainsText = 1

此脚本将获取包含文本类型列(nvarchar,varchar或text)的所有表,然后逐个执行SELECT以评估是否有任何行包含给定文本('BOLD')。