简体   繁体   中英

IN statement error in SQL triggers

I have a trigger that insert value to a another table based on a condition, in my condition thare is an IN statement within IF condition when im trying to insert multiple values using "INSERT INTO SELECT FROM" it returns following error "Subquery returned more than 1 value. This is not permitted when..."

here is my code

    ALTER TRIGGER [dbo].[WentOut] ON  [dbo].[TB_EVENT_LOG]
       AFTER INSERT
    AS 
    BEGIN

    DECLARE @AID int

        SET NOCOUNT ON;
        IF ((SELECT  nTNAEvent from inserted) IN(1,2,3))    
        BEGIN

            INSERT INTO Cen.WentOutLog  (AutoID, nUserID, nOutDateTime,nOutTNAEvent ,nReaderID) select nEventLogIdn,nUserID, nDateTime,nTNAEvent, nReaderIdn from inserted 

        END
END

it works for single value but not for multiple value inserting "INSERT INTO SELECT FROM" thanks in advance

As mentioned by Mitch trigger doesn't fire for each row. If am not wrong this is what you need.

ALTER TRIGGER [dbo].[WentOut]
ON [dbo].[TB_EVENT_LOG]
AFTER INSERT
AS
  BEGIN
      DECLARE @AID INT

      SET NOCOUNT ON;

      IF EXISTS(SELECT nTNAEvent
                FROM   inserted
                WHERE  nTNAEvent IN ( 1, 2, 3 ))
        BEGIN
            INSERT INTO Cen.WentOutLog
                        (AutoID,nUserID,nOutDateTime,nOutTNAEvent,
                         nReaderID)
            SELECT nEventLogIdn,nUserID,nDateTime,nTNAEvent,
                   nReaderIdn
            FROM   inserted
            WHERE  nTNAEvent IN ( 1, 2, 3 )
        END
      IF EXISTS(SELECT nTNAEvent
                FROM   inserted
                WHERE  nTNAEvent IN ( 0 ))
        BEGIN
        --statement
        END
  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