SQL Server:在数据库中查找相关列

时间:2014-04-30 16:00:04

标签: sql sql-server tsql

我试图在我的数据库中找到一个表包含两列,但我的代码不能正常工作

SELECT 
    t.name AS table_name,
    SCHEMA_NAME(schema_id) AS schema_name,
    c.name, d.name
FROM 
    sys.tables AS t
INNER JOIN 
    sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
INNER JOIN 
    sys.columns d ON t.OBJECT_ID = c.OBJECT_ID
WHERE 
    c.name = 'value1' AND d.name = 'value2'
ORDER BY 
    schema_name, table_name;

1 个答案:

答案 0 :(得分:0)

我的方法将第二个表(c)与第三个表(d)连接在一起,内连接意味着object_id两个表应该是相同的。
这里唯一的错误就是错误的加入... ON t.OBJECT_ID = c.OBJECT_ID

SELECT 
    t.name AS table_name,
    SCHEMA_NAME(schema_id) AS schema_name,
    c.name, d.name
FROM 
    sys.tables AS t
INNER JOIN 
    sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
INNER JOIN 
    sys.columns d ON c.OBJECT_ID = d.OBJECT_ID
WHERE 
    c.name = 'value1' AND d.name = 'value2'
ORDER BY 
    schema_name, table_name;