我的SQL Server数据库中有11个表,这些表具有相同的列,10个是子表,1个是主表,将合并10个表中的数据。这10个表会不时更新,下面是我的11个表中的列:
[DATE], [SOURCE], [DESTINATION], [REFERENCE#], [ITEMCODE], [DESCRIPTION],
[UM], [PRICE], [QTY], [AMOUNT], [MFGDATE], [EXPDATE], [LOT#], [TRANS], [CONSIGNOR], [DRDATE]
当用户更新表(即Table1
)时,应基于SOURCE
和DESTINATION
列自动更新主表。我知道有一个Merge
语句,您可以在其中同时更新,插入和删除所有语句,但是我的问题是删除,因为Table1
与主表,它将删除Table1
中不存在的主表中的其余数据。
我是SQL Server的新手,我自己无法做到这一点,这就是为什么我也在这里寻求想法和帮助。
答案 0 :(得分:1)
您可以尝试在Table1
表上使用插入后触发器:
CREATE TRIGGER your_trigger
ON Table1
AFTER INSERT AS
BEGIN
UPDATE a
SET SOURCE = b.SOURCE, DESTINATION = b.DESTINATION
FROM Main a
INNER JOIN INSERTED b
ON a.ID = b.ID
END
GO
我假设Table1
和主表是通过称为Id
的列连接的。但是,您可以更新联接逻辑以使用应确定如何连接两个表的任何列。
答案 1 :(得分:0)
在阅读您的评论和建议并在其他网站上阅读了很多之后,我提出了以下建议:
MERGE DelTrans2 as trgt
USING testTable1 src
ON trgt.SOURCE = Src.SOURCE
AND trgt.DESTINATION = Src.DESTINATION
AND trgt.REFERENCE# = Src.REFERENCE#
AND trgt.ITEMCODE = Src.ITEMCODE
AND trgt.ID = Src.ID
WHEN NOT MATCHED BY TARGET
AND Src.ID = 1001 THEN
INSERT(DATE, SOURCE, DESTINATION, REFERENCE#, ITEMCODE, DESCRIPTION, UM, PRICE, QTY, AMOUNT, MFGDATE, EXPDATE, LOT#, TRANS, CONSIGNOR, DRDATE, ID)
VALUES(DATE, SOURCE, DESTINATION, REFERENCE#, ITEMCODE, DESCRIPTION, UM, PRICE, QTY, AMOUNT, MFGDATE, EXPDATE, LOT#, TRANS, CONSIGNOR, DRDATE, ID)
WHEN MATCHED AND
(
ISNULL(trgt.DATE, '') <> ISNULL(Src.DATE, '')
OR
ISNULL(trgt.SOURCE, '') <> ISNULL(Src.SOURCE, '')
OR
ISNULL(trgt.DESTINATION, '') <> ISNULL(Src.DESTINATION, '')
OR
ISNULL(trgt.REFERENCE#, '') <> ISNULL(Src.REFERENCE#, '')
OR
ISNULL(trgt.ITEMCODE, '') <> ISNULL(Src.ITEMCODE, '')
OR
ISNULL(trgt.DESCRIPTION, '') <> ISNULL(Src.DESCRIPTION, '')
OR
ISNULL(trgt.UM, '') <> ISNULL(Src.UM, '')
OR
ISNULL(trgt.PRICE, '') <> ISNULL(Src.PRICE, '')
OR
ISNULL(trgt.QTY, '') <> ISNULL(Src.QTY, '')
OR
ISNULL(trgt.AMOUNT, '') <> ISNULL(Src.AMOUNT, '')
OR
ISNULL(trgt.MFGDATE, '') <> ISNULL(Src.MFGDATE, '')
OR
ISNULL(trgt.EXPDATE, '') <> ISNULL(Src.EXPDATE, '')
OR
ISNULL(trgt.LOT#, '') <> ISNULL(Src.LOT#, '')
OR
ISNULL(trgt.TRANS, '') <> ISNULL(Src.TRANS, '')
OR
ISNULL(trgt.CONSIGNOR, '') <> ISNULL(Src.CONSIGNOR, '')
OR
ISNULL(trgt.DRDATE, '') <> ISNULL(Src.DRDATE, '')
OR
ISNULL(trgt.ID, '') <> ISNULL(Src.ID, '')
)
AND Src.ID = 1001
THEN
UPDATE SET DATE = Src.DATE, SOURCE = Src.SOURCE, DESTINATION = Src.DESTINATION, REFERENCE# = Src.REFERENCE#, ITEMCODE = Src.ITEMCODE, DESCRIPTION = Src.DESCRIPTION, UM = Src.UM, PRICE = Src.PRICE, QTY = Src.QTY, AMOUNT = Src.AMOUNT, MFGDATE = Src.MFGDATE, EXPDATE = Src.EXPDATE, LOT# = Src.LOT#, TRANS = Src.TRANS, CONSIGNOR = Src.CONSIGNOR, DRDATE = Src.DRDATE, ID = Src.ID
WHEN NOT MATCHED BY SOURCE
AND trgt.ID = 1001 THEN
DELETE;
我知道这不是最有效的方法,但这可以满足我的需求。
谢谢您的帮助。