在SQL Server中找出两个表之间的差异

时间:2016-09-06 05:07:23

标签: sql-server difference

我有这个查询从源表返回27074行:

SELECT  
    [DOC NO]
    ,[LineNumber]
    ,[SHEET]
    ,[TestPkgNo]
    ,[ITEM CODE]
FROM 
    [excel].[dbo].[MTO2]

这一个(第二个表)

SELECT  
    DocumentNumber, LineNumber, SheetNumber, PackageNumber, ItemCode
FROM 
    [SPMS2].[dbo].[Materials] 
JOIN
    Lines ON materials.LineId = Lines.Id
JOIN  
    MaterialDescriptions ON MaterialDescriptions.Id = Materials.MaterialDescriptionId
JOIN
    TestPackages ON TestPackages.Id = Materials.TestPackageId

这会返回27032行。

我想找到两个表之间的区别,我的意思是结果应该是这样的:

doc line sheet testpack  sourcetable  secondtable
**   *   *      *          ok           not ok 

1 个答案:

答案 0 :(得分:1)

此查询将返回源表中存在但在第二个表中不存在的所有记录。

SELECT  
     [DOC NO]
    ,[LineNumber]
    ,[SHEET]
    ,[TestPkgNo]
    ,[ITEM CODE]
FROM 
    [excel].[dbo].[MTO2] sourcetable

LEFT JOIN
    (
        SELECT  
            DocumentNumber, LineNumber, SheetNumber, PackageNumber, ItemCode
        FROM 
            [SPMS2].[dbo].[Materials] 
        JOIN
            Lines ON materials.LineId = Lines.Id
        JOIN  
            MaterialDescriptions ON MaterialDescriptions.Id = Materials.MaterialDescriptionId
        JOIN
            TestPackages ON TestPackages.Id = Materials.TestPackageId
    ) secondtable
ON sourcetable.[DOC NO] = secondtable.DocumentNumber -- Remove conditions that are not needed
AND sourcetable.[LineNumber] = secondtable.LineNumber -- Remove conditions that are not needed
AND sourcetable.[SHEET] = secondtable.SheetNumber -- Remove conditions that are not needed
AND sourcetable.[TestPkgNo] = secondtable.PackageNumber -- Remove conditions that are not needed
AND sourcetable.[ITEM CODE] = secondtable.ItemCode  -- Remove conditions that are not needed

WHERE secondtable.DocumentNumber IS NULL -- Assuming DocumentNumber is a non-nullable column