1

我正在使用此代码段在数据库的任何表中查找特定字符串!

DECLARE @searchstring  NVARCHAR(255)
SET @searchstring = '%foo%'

DECLARE @sql NVARCHAR(max)

SELECT @sql = STUFF((
    SELECT ' UNION ALL SELECT ' + COLUMN_NAME + ' ' +
    ' FROM ' + TABLE_NAME + 
    ' WHERE ' + COLUMN_NAME + ' LIKE ''' + @searchstring + ''''
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE DATA_TYPE in ('nvarchar', 'varchar', 'char','nchar')
    FOR XML PATH('')
) ,1, 11, '')


exec (@sql)

但我想获得这些条目的主键值!

要获取我使用的特定表的主键

SELECT ccu.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
    INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON tc.CONSTRAINT_NAME = ccu.Constraint_name 
    WHERE tc.CONSTRAINT_TYPE = 'Primary Key' 
    AND tc.TABLE_NAME = 'tbl_table'

但我不能将两者结合起来?!

4

1 回答 1

0

有些表的主键中可能有多个列,而另一些表可能没有主键。这使这项任务变得更加困难,并且结果列需要是一列中的主键值列表。

SELECT @sql = STUFF((
    SELECT ' UNION ALL SELECT ' + QUOTENAME(C.COLUMN_NAME) + ', ' +
               ISNULL(STUFF((SELECT '+'', ''+CAST('+QUOTENAME(COLUMN_NAME)+' AS VARCHAR(MAX))'
                             FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
                               INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CU
                                 ON TC.CONSTRAINT_NAME = CU.CONSTRAINT_NAME AND
                                    TC.TABLE_NAME = CU.TABLE_NAME
                             WHERE CU.TABLE_NAME = C.TABLE_NAME AND
                                   TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
                             FOR XML PATH('')), 1, 6, ''), '''''')+' AS PrimaryKeys'+
    ' FROM ' + QUOTENAME(C.TABLE_NAME) + 
    ' WHERE ' + QUOTENAME(C.COLUMN_NAME) + ' LIKE ''' + @searchstring + ''''
    FROM INFORMATION_SCHEMA.COLUMNS AS C
    WHERE C.DATA_TYPE in ('nvarchar', 'varchar', 'char','nchar')
    ORDER BY C.TABLE_NAME
    FOR XML PATH('')
) ,1, 11, '')

SQL小提琴

使用小提琴中的表生成的查询将如下所示。

SELECT [Col], 
       CAST([ID] AS VARCHAR(MAX)) AS PrimaryKeys 
FROM [T1] 
WHERE [Col] LIKE '%foo%' 
UNION ALL 
SELECT [Col], 
       CAST([Col] AS VARCHAR(MAX))+', '+CAST([ID] AS VARCHAR(MAX)) AS PrimaryKeys 
FROM [T2] 
WHERE [Col] LIKE '%foo%' 
UNION ALL 
SELECT [Col], 
       '' AS PrimaryKeys 
FROM [T3] 
WHERE [Col] LIKE '%foo%'
于 2013-08-08T09:49:04.680 回答