简体   繁体   中英

Trigger copy data from table2 when only one data in table1 inserted

I have this trigger

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 

however if i submit insert statement like this. It supposed to pull data from client table and insert in in the same row in which i insert ID and date, however it creates new records and put data in them.

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

it is not copping any data from clients table it just insert empty rows 如何从取件中选择*看起来像 Any Ideas what is going on and where is my mistake in this query

You need to use INSTEAD OF INSERT trigger or AFTER trigger with UPDATE statements

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    

AFTER TRIGGER

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   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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