在更新SQL Server中的现有值时,将现有列值插入新表中

时间:2014-12-02 12:08:24

标签: sql sql-server sql-server-2008 sql-server-2005

我是SQL Server新手。

我需要一个答案,我有一个表tblemployee,列是

empid,
name,
paddr1,
paddr2,
pcity,
pstate,
pzip,
caddr1,
caddr2,
ccity,
cstate,
czip

我有另一个表tblpaddresshistory,列是

paddrlistid,
paddr1,
paddr2,
pcity,
pstate,
pzip

我还有另一张表tblcaddresshistory,其中包含这些列

caddrlistid,
caddr1,
caddr2,
ccity,
cstate,
czip

以下是我的问题:当我更新tblemployee列值paddr1, paddr2, pcity, pstate, pzip, caddr1, caddr2, ccity, cstate, czip时,应将旧值插入tblpaddresshistorytblcaddresshistory以及新值值应在tblemployee中更新。

1 个答案:

答案 0 :(得分:0)

Try with this trigger

CREATE TRIGGER dbo.tr_tblemployee
ON dbo.tblemployee
AFTER UPDATE
AS
  BEGIN
      IF ( UPDATE(paddr1)
            OR UPDATE(paddr2)
            OR UPDATE (pcity)
            OR UPDATE(pstate)
            OR UPDATE(pzip) )
        BEGIN
            INSERT INTO dbo.tblpaddresshistory
                        (paddr1,
                         paddr2,
                         pcity,
                         pstate,
                         pzip)
            SELECT paddr1,
                   paddr2,
                   pcity,
                   pstate,
                   pzip
            FROM   deleted;
        END

      IF ( UPDATE(caddr1)
            OR UPDATE(caddr2)
            OR UPDATE (ccity)
            OR UPDATE(cstate)
            OR UPDATE(czip) )
        BEGIN
            INSERT INTO dbo.tblcaddresshistory
                        (caddr1,
                         caddr2,
                         ccity,
                         cstate,
                         czip)
            SELECT caddr1,
                   caddr2,
                   ccity,
                   cstate,
                   czip
            FROM   deleted;
        END
  END;