如何选择其中包含两个或更多特定列的数据库表?

时间:2016-07-28 16:32:02

标签: sql-server sql-server-2012

如何选择其中包含两个或更多特定列的数据库表?

此处显示的表格中包含CustomerName。要添加另一列来查找,似乎我可能必须在子查询中添加另一个子查询。

我正在寻找一个简单的查询,我可以添加x个列而不会增加复杂性。

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE t.name in (select t.name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID where c.name LIKE '%CustomerID%')
ORDER BY schema_name, table_name;

更新
想要使用LIKE运算符

1 个答案:

答案 0 :(得分:0)

假设您希望表中包含您提供的所有列名,那么没有子查询的简单方法可能是:

SELECT  t.name AS table_name,
        SCHEMA_NAME(t.schema_id) AS schema_name
FROM    sys.tables AS t
INNER JOIN sys.columns c ON t.object_id = c.object_id
WHERE    c.name IN('COL1', 'COL2') -- Column names in here
GROUP BY t.name, SCHEMA_NAME(t.schema_id)
HAVING COUNT(DISTINCT c.name) = 2 -- Match the count of columns in the IN criteria
ORDER BY SCHEMA_NAME(t.schema_id), t.name;