在 SQL 服务器中查找包含两个特定列的 table

Find table containing two particular columns in SQL Server

我想在 SQL 服务器中找到所有包含两个特定 separate 列的表。

第一列名称是"LIKE '%A%'"(意味着它包含子字符串"A"),第二列名称是"LIKE '%B%'"(意味着它包含子字符串"B") .

我写了下面的查询,我想检查一下它的正确性:

SELECT s.TABLE_NAME 
FROM (SELECT COLUMN_NAME, TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE COLUMN_NAME LIKE '%A%'
    UNION
    SELECT COLUMN_NAME, TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE COLUMN_NAME LIKE '%B%') s
WHERE EXISTS (SELECT COLUMN_NAME, s.TABLE_NAME 
              FROM INFORMATION_SCHEMA.COLUMNS
              WHERE COLUMN_NAME LIKE '%A%')
AND EXISTS (SELECT COLUMN_NAME, s.TABLE_NAME
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE COLUMN_NAME LIKE '%B%');  

那应该更容易:

SELECT s.TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES AS s
WHERE s.TABLE_TYPE='BASE TABLE'
AND EXISTS (SELECT 1 
              FROM INFORMATION_SCHEMA.COLUMNS
              WHERE TABLE_NAME=s.TABLE_NAME AND COLUMN_NAME LIKE '%A%')
AND EXISTS (SELECT 1
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_NAME=s.TABLE_NAME AND COLUMN_NAME LIKE '%B%');  

更新

使用此代码,您将找到符合这两个条件的所有列作为列表...

SELECT s.TABLE_NAME,listA,listB
FROM INFORMATION_SCHEMA.TABLES AS s
CROSS APPLY (SELECT STUFF(
             (
                 SELECT ', ' + COLUMN_NAME 
                 FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE TABLE_NAME=s.TABLE_NAME AND COLUMN_NAME LIKE '%med%'
                 ORDER BY ORDINAL_POSITION
                 FOR XML PATH('')
             ),1,2,'')
             ) AS columnsWithA(listA)
CROSS APPLY (SELECT STUFF(
             (
                 SELECT ', ' + COLUMN_NAME 
                 FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE TABLE_NAME=s.TABLE_NAME AND COLUMN_NAME LIKE 'kli%'
                 ORDER BY ORDINAL_POSITION
                 FOR XML PATH('')
             ),1,2,'')
             ) AS columnsWithB(listB)
WHERE s.TABLE_TYPE='BASE TABLE'
  AND listA IS NOT NULL AND listB IS NOT NULL

更新 2

最后 AND listA<>listB AND CHARINDEX(',',listA)=0 只要只有一列(=> 没有逗号),您就会排除相同的 listA 和 listB

设置逻辑来拯救!

SELECT DISTINCT TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS AS c
WHERE COLUMN_NAME LIKE '%A%' 
AND COLUMN_NAME NOT LIKE '%B%'

INTERSECT

SELECT DISTINCT TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS AS c
WHERE COLUMN_NAME LIKE '%B%' 
AND COLUMN_NAME NOT LIKE '%A%'

已更新以相互排除双重匹配。 删除了 TABLE 架构上的内部联接

一种方法只使用聚合和 having:

SELECT TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
GROPU BY TABLE_NAME
HAVING SUM(CASE WHEN COLUMN_NAME LIKE '%A%' THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN COLUMN_NAME LIKE '%B%' THEN 1 ELSE 0 END) > 0;

如有必要,您可以使用返回 INFORMATION_SCHEMA.COLUMNS 来获取列名——尽管这不是您的实际问题。