在SQL SERVER触发器中插入多行

时间:2015-01-05 05:48:25

标签: sql-server sql-server-2008 triggers

我需要使用触发器将多行插入另一个表,但它只会输入最后一条记录 我检查了stackoverflow中的其他帖子并没有得到答案,

这是我的触发器

IF(@TNAEventID IN(1,2,3))       
BEGIN
    INSERT INTO [Biostar].Cen.WentOutLog    (AutoID, nUserID, nOutDateTime,nOutTNAEvent ,nReaderID) values  (@AutoID,@UseID, @DateTime,@TNAEventID, @ReaderID )
END
else IF(@TNAEventID=0)      
BEGIN

    UPDATE Cen.WentOutLog Set  nINDateTime =@DateTime,nInTNAEvent = @TNAEventID  Where AutoID = (Select  top (1) AutoID from Cen.WentOutLog where nINDateTime is null AND  nOutDateTime<@DateTime AND  nUserID=@UseID order by nOutDateTime desc)
END
else
begin
    ....
end

先谢谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码,插入代码随时可用。

  

您可能需要更改UPDATE语句,因为我不知道是什么   你的数据:

INSERT INTO [Biostar].[Cen].[WentOutLog]
    ([AutoID], [nUserID], [nOutDateTime], [nOutTNAEvent], [nReaderID])
SELECT  [AutoID], [nUserID], [nOutDateTime], [nOutTNAEvent], [nReaderID]
FROM    INSERTED
WHERE   TNAEventID IN (1, 2, 3)

UPDATE  W
FROM    [Cen].[WentOutLog]
SET     W.[nINDateTime] = I.[DateTime],
        W.[nInTNAEvent] = I.[TNAEventID]
INNER JOIN INSERTED I ON W.[AutoID] = I.[AutoID]
WHERE   I.[TNAEventID] = 0
AND     W.[nINDateTime] IS NULL
AND     W.[nOutDateTime] < I.[DateTime]
AND     W.[nUserID] = I.[UserID]