我有两张结构相同的桌子。一个是Temp表,一个是主表。表名分别为PurchaseOrders_TEMP和PurchaseOrders。每天我用新数据刷新临时表并运行PROC以更新主表并进行更改和/或添加。我意识到如果PO上的PO和/或项目被完全删除,我会遇到问题。我的proc不会更新不在Temp表中的行。以下是PurchaseOrders的表定义。我需要一个新的PROC或对此PROC的更新,当它在TEMP表中不存在时,将PBSTAT更改为PBPO / PBITEM的'X'。
[dbo].[PurchaseOrders](
[ID] [int] IDENTITY(1,1) NOT NULL,
[PBPO] [int] NOT NULL,
[PBSEQ] [int] NOT NULL,
[PBITEM] [varchar](28) NOT NULL,
[PBDEL] [varchar](1) NULL,
[PBVEND] [varchar](9) NULL,
[PBTYPE] [varchar](1) NULL,
[PBLOC] [varchar](4) NULL,
[PBDSC1] [varchar](51) NULL,
[PBDSC2] [varchar](45) NULL,
[PBPDTE] [datetime] NULL,
[PBDUE] [datetime] NULL,
[XDPRVDT] [datetime] NULL,
[XDCURDT] [datetime] NULL,
[PBRDTE] [datetime] NULL,
[PBOQTY] [int] NULL,
[PBTQTY] [int] NULL,
[PBRQTY] [int] NULL,
[PBDQTY] [int] NULL,
[PBLQTY] [int] NULL,
[PBBQTY] [int] NULL,
[PBCOST] [float] NULL,
[EXTCOST] [float] NULL,
[PBCCTD] [datetime] NULL,
[PBCCTT] [int] NULL,
[PBCCTU] [varchar](15) NULL,
[PBLCGD] [datetime] NULL,
[PBLCGT] [int] NULL,
[PBUSER] [varchar](12) NULL,
[PASTAT] [varchar](1) NULL,
[PABUYR] [varchar](3) NULL,
[PAPAD3] [varchar](45) NULL,
[PAPPHN] [varchar](30) NULL,
[PACONF] [varchar](39) NULL,
[Comment] [varchar](max) NULL
以下是我为更新数据而运行的当前Proc。
ALTER PROCEDURE [dbo].[UpdateExistingPurchaseOrders]
AS
BEGIN
SET NOCOUNT ON;
UPDATE
p
SET
p.PBDEL = pt.PBDEL,
p.PBVEND = pt.PBVEND,
p.PBTYPE = pt.PBTYPE,
p.PBLOC = pt.PBLOC,
p.PBDSC1 = pt.PBDSC1,
p.PBDSC2 = pt.PBDSC2,
p.PBPDTE = pt.PBPDTE,
p.PBDUE = pt.PBDUE,
p.PBRDTE = pt.PBRDTE,
p.PBOQTY = pt.PBOQTY,
p.PBTQTY = pt.PBTQTY,
p.PBRQTY = pt.PBRQTY,
p.PBDQTY = pt.PBDQTY,
p.PBLQTY = pt.PBLQTY,
p.PBBQTY = pt.PBBQTY,
p.PBCOST = pt.PBCOST,
p.EXTCOST = pt.EXTCOST,
p.PBCCTD = pt.PBCCTD,
p.PBCCTT = pt.PBCCTT,
p.PBCCTU = pt.PBCCTU,
p.PBLCGD = pt.PBLCGD,
p.PBLCGT = pt.PBLCGT,
p.PBUSER = pt.PBUSER,
p.PASTAT = pt.PASTAT,
p.PABUYR = pt.PABUYR,
p.PAPAD3 = pt.PAPAD3,
p.PAPPHN = pt.PAPPHN,
p.PACONF = pt.PACONF
FROM
dbo.PurchaseOrders_TEMP pt
LEFT OUTER JOIN dbo.PurchaseOrders p
ON p.PBPO = pt.PBPO
AND p.PBSEQ = pt.PBSEQ
WHERE
p.PBPO IS NOT NULL
AND p.PBSEQ IS NOT NULL
END
答案 0 :(得分:1)
您可以使用MERGE语句从源查询中的数据修改目标表中的数据。文档中的前两个示例显示了如何根据是否找到源行来插入/更新或更新/删除。
在你的情况下,你必须写这样的东西:
MERGE dbo.PurchaseOrders AS target
USING (SELECT ... FROM PurchaseOrders_TEMP) AS source (...)
ON (ON target.PBPO = source.PBPO
AND target.PBSEQ = source.PBSEQ)
WHEN NOT MATCHED BY SOURCE
THEN DELETE
WHEN NOT MATCHED BY TARGET
THEN INSERT (....)
VALUES (....)
WHEN MATCHED
THEN UPDATE
SET ...
答案 1 :(得分:0)
这是我想出的答案......
UPDATE
p
SET
p.PASTAT = 'X'
FROM
dbo.PurchaseOrders_TEMP pt
LEFT JOIN dbo.PurchaseOrders p ON
p.PBPO = pt.PBPO
AND p.PBSEQ = pt.PBSEQ
WHERE
pt.PBPO IS NULL
AND pt.PBSEQ IS NULL
AND p.PASTAT <> 'X'
END