哪个表包含此数据+ SQL

时间:2012-02-11 17:03:04

标签: sql sql-server sql-server-2008

我有一个包含100个表的数据库。 我怎么知道哪个表包含特定文本。

例如哪个表包含文本'Assumed Life Claims'

我可以暗示这个字段是varchar

SQL SERVER 2008

1 个答案:

答案 0 :(得分:0)

ypercube的建议完全正确。这是一个实现:

DECLARE @searchText VARCHAR(100)
SET @searchText = 'Assumed Life Claims'

DECLARE @sqlText VARCHAR(8000)
DECLARE @MaxId INT
DECLARE @CurId INT
DECLARE @possibleColumns TABLE (Id INT IDENTITY(1, 1) NOT NULL PRIMARY KEY
                               ,sqlText VARCHAR(8000))
INSERT INTO @possibleColumns(sqlText)
SELECT 'IF EXISTS (SELECT * FROM ' + c.TABLE_NAME + ' WHERE ' + c.COLUMN_NAME + ' = ''' + @searchText + ''') PRINT '' searchText=' + @searchText + ' was found in ' + c.TABLE_NAME + '.' + c.COLUMN_NAME + ''''
  FROM INFORMATION_SCHEMA.COLUMNS c
    -- Using hint that this field is a varchar
 WHERE c.DATA_TYPE = 'varchar'

SELECT @CurId = MIN(pc.Id)
       ,@MaxId = MAX(pc.Id)
  FROM @possibleColumns pc

WHILE (@CurId <= @MaxId)
BEGIN
    SELECT @sqlText = pc.sqlText
      FROM @possibleColumns pc
     WHERE pc.Id = @CurId

    -- For testing (uncomment)
    --PRINT @sqlText

    EXEC(@sqlText)

    -- Increment counter
    SET @CurId = @CurId + 1
END