使用sql触发器将数据保存在两个表中

时间:2013-11-12 18:41:58

标签: tsql sql-server-2005 triggers synchronization

我有一个Products表,其中包含一个属性,该属性将通过最终用户的ERP更新进行更新。当发生这种情况时,我需要在另一个表中复制更新。我对创建T-SQL触发器没有任何经验,但我相信它会实现我的目标。

实施例: 在IC_Products表中:

Productkey = 456
StockLocation = ‘GA-07-A250’

IC_ProductCustomFields表中(将开始相同,因为我将运行一个脚本来实现它):

Productkey = 456
CustomFieldKey = 13 
Value = ‘GA-07-A250’

IC_Products.StockLocation列更新后,我希望新IC_ProductCustomFields.Value中的值也会立即自动更新。
如果在IC_Products中创建了新记录,那么我希望在IC_ProductCustomFields中创建新记录。

我想知道如何编写触发器脚本以及如何实现它。我正在使用SQL Server 2005。

1 个答案:

答案 0 :(得分:0)

你想要这样的东西:

CREATE TRIGGER [dbo].[tr_Products_SyncCustomFields] ON [dbo].[IC_Products] 
FOR INSERT, UPDATE
AS
    -- First, we'll handle the update. If the record doesn't exist, we'll handle that second
    UPDATE IC_ProductCustomFields
    SET Value = inserted.StockLocation
    FROM IC_ProductCustomFields cf
        INNER JOIN inserted -- Yes, we want inserted. In triggers you just get inserted and deleted
            ON cf.Productkey = inserted.Productkey AND CustomFieldKey = 13;

    -- Now handle the insert where required. Note the NOT EXISTS criteria
    INSERT INTO IC_ProductCustomFields (Productkey, CustomFieldKey, Value)
    SELECT Productkey, CustomFieldKey, Value
    FROM inserted
    WHERE NOT EXISTS 
    (
        SELECT * 
        FROM IC_ProductCustomFields 
        WHERE Productkey = inserted.Productkey AND CustomFieldKey = 13
    );

GO

我认为,您可以为插入和更新执行单独的触发器,但如果自定义字段不同步,这也会产生恢复(假定的?)不变量的副作用;即使在更新中,如果自定义字段不存在,也会根据需要插入新记录,以使其恢复符合您的规范。