生成报告,显示两个SQL表之间匹配的Ids

我有一个SQL查询,我正在运行插入值table1到table2只有在表行的ID匹配匹配:

UPDATE PT SET CreditInvoiceAmount = CSV.CreditInvoiceAmount ,CreditInvoiceDate = CSV.CreditInvoiceDate ,CreditInvoiceNumber = CSV.CreditInvoiceNumber ,CreditDeniedDate = CSV.CreditDeniedDate ,CreditDeniedReasonId = CSV.CreditDeniedReasonId ,CreditDeniedNotes = CSV.CreditDeniedNotes ,StatusId = CASE WHEN CSV.CreditInvoiceDate IS NULL AND CSV.CreditDeniedDate IS NOT NULL THEN 7 ELSE 8 END FROM PermanentTable PT INNER JOIN TemporaryCsvUpload CSV ON PT.Id = CSV.Id 

我会说在临时表中约60%的ID与永久表中的ID相匹配。 我想生成一些报告来显示哪些ID匹配,哪些没有。 我显示这些信息的格式并不重要(HTML表格,Excel表格,不pipe)。 我不知道如何使用查询来获取该信息,以便我可以显示它。 谢谢你的帮助!

要显示所有的ID,以及它们是在一个还是两个表中,试试这个; 它将返回至less在一个表中的ID列表,并带有一个标志,指出它们出现在哪个或哪些表中:

 Select ISNULL(p.ID, t.ID) as ID , case when p.ID is not null then 'Y' else 'N' end as InPermanentTable , case when t.ID is not null then 'Y' else 'N' end as InTemporaryTable from PermanentTable p full outer join TemporaryCsvUpload t on p.ID = t.ID 

要从临时表中返回ID以及是否在永久表中的标志,请使用以下命令:

 Select t.ID , case when p.ID is not null then 'Y' else 'N' end as InPermanentTable from TemporaryCsvUpload t left join PermanentTable p on p.ID = t.ID 

MERGE声明将适合你正在寻找的东西。 它可以更新那些匹配,插入那些不匹配,并报告给你什么匹配什么没有。 最好将输出logging到另一个表中。

 MERGE PermanentTable P --target USING TemporaryCsvUpload T --source ON P.Id = T.Id WHEN MATCHED THEN UPDATE P SET CreditInvoiceAmount = T.CreditInvoiceAmount ,CreditInvoiceDate = T.CreditInvoiceDate ,CreditInvoiceNumber = T.CreditInvoiceNumber ,CreditDeniedDate = T.CreditDeniedDate ,CreditDeniedReasonId = T.CreditDeniedReasonId ,CreditDeniedNotes = T.CreditDeniedNotes ,StatusId = CASE WHEN T.CreditInvoiceDate IS NULL AND T.CreditDeniedDate IS NOT NULL THEN 7 ELSE 8 END WHEN NOT MATCHED THEN INSERT (P columns go here) VALUES (T columns go here) OUTPUT $action, Inserted.Id --Inserted will show both inserted and updated to IDs , Deleted.Id --Deleted will show IDs that were changed in the UPDATE 

由于你只是更新/插入,当动作是更新时,插入和删除标识将是相同的。

您可以更改WHEN NOT MATCHED以便login到单独的表,而不是永久表。