我需要创建一个触发器,在插入table1时,检查table2中3列的相同值是否匹配,如果不匹配则将该行插入table2。如果匹配,则更新匹配的行。这是我到目前为止所收集的内容,但它并没有进行我需要的IF EXISTS检查。由于从未使用触发器,我不确定在这种情况下如何构造它。
CREATE TRIGGER Trigger_Name on Table_Name
FOR INSERT
AS
BEGIN
INSERT INTO
TABLE 2
(
Col1,
Col2,
Col3,
Col4
)
SELECT
(
Col1,
Col2,
Col3,
Col4
)
FROM
INSERTED
GO
IF EXISTS标准需要查看table1.col1 = table2.col1,table1.col2 = table2.col2,table1.col3,table2.col3
使用SQL Server 2008.非常感谢任何帮助
答案 0 :(得分:0)
UPDATE table2
SET col1 = inserted.col1
, col2 = inserted.col2
, col3 = inserted.col3
, col4 = inserted.col4
FROM table2
INNER
JOIN inserted
ON inserted.col1 = table2.col1
AND inserted.col2 = table2.col2
AND inserted.col3 = table2.col3
;
INSERT INTO table2 (col1, col2, col3, col4)
SELECT col1
, col2
, col3
, col4
FROM inserted
WHERE NOT EXISTS (
SELECT *
FROM table1
WHERE col1 = inserted.col1
AND col2 = inserted.col2
AND col3 = inserted.col3
)
;