SQL Server表中应具有相同列的列中的不匹配

时间:2017-06-20 00:27:18

标签: sql sql-server

我们如何识别不在表中的列应该与具有SQL查询的另一个表具有相同的列?

例如,表Transactions应与表Transactions_History具有相同的列。也可以有多个历史记录表,例如Transactions_History01,Transactions_History02等。

问题是当列被添加到Transactions时,它没有被添加到历史表中。

2 个答案:

答案 0 :(得分:1)

使用INFORMATION_SCHEMA.COLUMNS,您可以通过以下方式实现此目的:

SELECT DISTINCT BaseTable = C1.TABLE_NAME, MatchedTable = C2.TABLE_NAME, MissingColumn = C1.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS AS C1
JOIN INFORMATION_SCHEMA.COLUMNS AS C2
    ON C2.TABLE_NAME LIKE C1.TABLE_NAME + '[_]_%'
WHERE C1.TABLE_NAME = 'BaseTable'
AND NOT EXISTS
(
    SELECT 1
    FROM INFORMATION_SCHEMA.COLUMNS C3
    WHERE C3.TABLE_NAME = C2.TABLE_NAME
    AND C3.COLUMN_NAME = C1.COLUMN_NAME
);

注意:如果对于特定表格不是这样,您可以省略WHERE C1.TABLE_NAME = 'BaseTable'部分,并且您应该能够看到基表具有相应_something表的任何表的所有不匹配列

编辑:以下是如何用sys表做同样的事情:

SELECT DISTINCT BaseTable = T1.Name, MatchedTable = T2.Name, MissingColumn = C1.Name
FROM sys.tables AS T1
JOIN sys.columns AS C1
    ON C1.[object_id] = T1.[object_id]
JOIN sys.tables AS T2
    ON T2.Name LIKE T1.Name + '[_]_%'
JOIN sys.columns AS C2
    ON C2.[object_id] = T2.[object_id]
WHERE T1.[object_id] = OBJECT_ID('MySchema.BaseTable')
AND NOT EXISTS
(
    SELECT 1
    FROM sys.tables AS T3
    JOIN sys.columns AS C3
        ON C3.[object_id] = T3.[object_id]
    WHERE T3.[object_id] = T2.[object_id]
    AND C3.Name = C1.Name
);

答案 1 :(得分:0)

您可以查询information_schema视图以识别和比较每个配对表的列。