插入更新触发器

时间:2011-12-02 05:49:10

标签: sql-server tsql

使用触发器:

我们有两个表,如名为table1和table2

如果我们在table1中插入任何东西而不是它应该插入到table2中,并且必须与table1比较是否已存在该行或数据.. 如果存在那么它应该更新到table1,否则它应该作为新行插入table1 ..

1 个答案:

答案 0 :(得分:0)

您可以使用以下触发器来识别表格的插入或更新或删除状态

CREATE TRIGGER Audit 
    ON dbo.Employee 
    FOR INSERT, UPDATE, DELETE 
AS 
    IF (SELECT COUNT(*) FROM inserted) > 0 
    BEGIN 
        IF (SELECT COUNT(*) FROM deleted) > 0 
        BEGIN 
            -- update! 
            INSERT AuditEmployee 
            (EmployeeID, UserName, Operation) 
            SELECT EmployeeID, SUSER_SNAME(), 'U' 
            FROM inserted 
        END 
        ELSE 
        BEGIN 
            -- insert! 
            INSERT AuditEmployee 
            (EmployeeID, UserName, Operation) 
            SELECT EmployeeID, SUSER_SNAME(), 'I' 
            FROM inserted 
        END 
    END 
    ELSE 
    BEGIN 
        -- delete! 
        INSERT AuditEmployee 
        (EmployeeID, UserName, Operation) 
        SELECT EmployeeID, SUSER_SNAME(), 'D' 
        FROM deleted 
    END 
GO