当table1中只插入一个数据时,从table2触发复制数据

时间:2013-02-20 19:18:23

标签: sql sql-server triggers

我有这个触发器

CREATE TRIGGER TriggerPickup
    ON dbo.Pickup
    AFTER INSERT 
    AS BEGIN
INSERT INTO dbo.Pickup( PickupProxy,PickupHispanic,EthnCode,CategCode,AgencyID)
         SELECT
              Clients.ClientProxy, Clients.Hispanic, Clients.EthnCode, Clients.CategCode,Clients.AgencyID
         FROM
             dbo.Clients,Pickup
             where   Pickup.ClientID =Clients.ClientID
    END 

但是如果我像这样提交插入语句。它应该从客户端表中提取数据并插入到我插入ID和日期的同一行中,但它会创建新记录并将数据放入其中。

INSERT INTO Pickup (ClientID, PickupDate)
VALUES (13144, '2010-11-20');

它不会从客户端表中包含任何数据,只是插入空行 how does select * from pickup looks like 任何想法发生了什么以及我在这个查询中的错误

1 个答案:

答案 0 :(得分:1)

您需要使用INSTEAD OF INSERT触发器或AFTER触发器和UPDATE语句

CREATE TRIGGER TriggerPickup ON dbo.Pickup
INSTEAD OF INSERT
AS BEGIN
  INSERT dbo.Pickup( PickupDate,
                    PickupProxy, PickupHispanic, EthnCode, CategCode, AgencyID)
  SELECT i.PickupDate, 
         c.ClientProxy, c.Hispanic, c.EthnCode, c.CategCode, c.AgencyID
  FROM dbo.Clients c JOIN inserted i ON i.ClientID = c.ClientID
END    

触发后

CREATE TRIGGER TriggerPickup ON dbo.Pickup
FOR INSERT
AS BEGIN
  UPDATE p
  SET p.PickupProxy = c.ClientProxy,
      p.PickupHispanic = c.PickupHispanic,
      p.EthnCode = c.EthnCode,
      p.CategCode = c.CategCode,
      p.AgencyID = c.AgencyID
  FROM inserted i JOIN dbo.Clients c ON i.ClientID = c.ClientID
                  JOIN dbo.Pickup p ON i.PickupID = p.PickupID
END