查找两个表之间的增量

时间:2018-01-22 14:56:45

标签: sql-server tsql

我有两个表,我们称之为表A和表B.两种不同的大小但具有相同的主键(ID)。变量字段是(Name)。我想从表B中返回以下行:

  1. 数据已更改
  2. 之前不存在数据

    返回的数据将有一个标记为comments的附加列,每次执行SQL时都将值设置为高于此值。我在下面编写了T-SQL,但是有更好的方法吗?

    SELECT [ID]
    ,[Name]
    ,'Data did not exist before' AS [Comment]
    FROM TABLENAMEB
    WHERE [ID] NOT IN (SELECT [ID] FROM #TABLENAMEA)
    UNION
    SELECT B.[ID]
    ,B.[Name]
    ,'Data has changed' AS [Comment]
    FROM  TABLENAMEB B
    LEFT JOIN TABLENAMEA A ON B.[ID] = A.[ID] 
    WHERE A.[Name] != B.[Name]
    

3 个答案:

答案 0 :(得分:3)

这样的事情:

DECLARE @tblA TABLE(ID INT, Name VARCHAR(100));
INSERT INTO @tblA VALUES(1,'test1'),(2,'test2'),(4,'test4');

DECLARE @tblB TABLE(ID INT, Name VARCHAR(100));
INSERT INTO @tblB VALUES(2,'test2'),(3,'test3'),(4,'different');

SELECT CASE WHEN A.ID IS NULL THEN 'missing in A'
            WHEN B.ID IS NULL THEN 'missing in B'
            WHEN A.Name<>B.Name THEN 'different'
            ELSE 'okay' END AS Comment
            ,*
FROM @tblA AS A
FULL OUTER JOIN @tblB AS B ON A.ID=B.ID

结果

Comment         ID    Name  ID      Name
missing in B    1     test1 NULL    NULL
okay            2     test2 2       test2
different       4     test4 4       different
missing in A    NULL  NULL  3       test3

答案 1 :(得分:1)

您可以使用左连接和case来获得相同的结果:

SELECT [ID]
      ,[Name]
      ,CASE 
       WHEN A.[Name] IS NULL THEN -- Assuming `Name` in table a is not nullable.
           'Data did not exist before'
       WHEN B.[Name] != A.[Name THEN 
           'Data has changed'
       ELSE 
           ''
       END As [Comment]
FROM TABLENAMEB As B
LEFT JOIN #TABLENAMEA As A ON B.[ID] = A.[ID]

答案 2 :(得分:0)

编辑:我刚刚注意到您正在使用2008.以下功能将毫无用处。

您正在使用T-SQL编写此代码,因此您正在使用SQL Server。查看专门为回答您的问题而设计的这两个功能中的任何一个:

  1. 更改数据捕获
  2. 时间表