简体   繁体   English

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

[英]Inserting existing column value into a new table when updating the existing value in SQL Server

I'm new to SQL Server. 我是SQL Server的新手。

I need a one answer that it is, I have a table tblemployee and the columns are 我需要一个答案,我有一个表tblemployee ,列是

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

I have a another table tblpaddresshistory and the columns are 我有另一个表tblpaddresshistory并且列是

paddrlistid,
paddr1,
paddr2,
pcity,
pstate,
pzip

and I have yet another table tblcaddresshistory with these columns 我还有另一个表tblcaddresshistory与这些列

caddrlistid,
caddr1,
caddr2,
ccity,
cstate,
czip

Here is my question: when I'm updating the tblemployee of column values paddr1, paddr2, pcity, pstate, pzip, caddr1, caddr2, ccity, cstate, czip , the old values should be inserted into tblpaddresshistory and tblcaddresshistory and new values should be updated in tblemployee . 这里是我的问题:当我更新tblemployee列值的paddr1, paddr2, pcity, pstate, pzip, caddr1, caddr2, ccity, cstate, czip ,旧的值应该插入tblpaddresshistorytblcaddresshistory和新的价值观应该是在tblemployee更新。

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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM