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

时间:2015-07-30 16:32:22

标签: c# sql sql-server asp.net-mvc excel

我正在运行一个SQL查询,只是在表格行的ID匹配的情况下,将值从table1插入到table2:

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表格,等等)。我不确定如何使用查询来获取该信息,以便我可以显示它。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

要显示所有ID,以及它们是在一个还是两个表中,请尝试这样做;它将返回至少一个表中的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

答案 1 :(得分:1)

MERGE语句符合您的要求。它能够更新那些匹配的,插入那些不匹配的,并向您报告匹配的内容和不匹配的内容。最好将输出记录到另一个表中。

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

由于您只是更新/插入,当操作是UPDATE时,插入和删除的ID将是相同的。

您也可以更改WHEN NOT MATCHED以登录到单独的表,而不是更改为永久表。