简体   繁体   English

如何在插入触发器SQL Server中检索Identity列值

[英]How to Retrieve the Identity column value in an insert trigger SQL Server

I have two tables that are identical except one has an identity column and the other doesn't. 我有两个相同的表,除了其中一个具有标识列,而另一个则没有。 Instead the second table uses the value of the identity column from the first table. 相反,第二个表使用第一个表中的identity列的值。 I thought I would insert into the second table as a trigger when a record is inserted into the first table. 我以为当一条记录插入到第一张表中时,我将其插入到第二张表中作为触发器。 I cannot seem to get syntax right. 我似乎语法不正确。

Null is being returned from the identity column @EDVisitId. 从标识列@EDVisitId返回Null。

ALTER TRIGGER [dbo].[trgInserterrEDVisitOriginal] ON [dbo].[errEDVisit]
AFTER INSERT
AS


--Name:  Bob Avallone
--Date:  6-15-2017
--
--  The purpose of this trigger is to insert a record into errEDVisitOriginal
--  whenever a new errEDVisit is inserted.

--XXXXXXXXXX



    declare @EDVisitId  int
    declare @SubmissionControlID INT


Select  @EDVisitId = EDVisitID from inserted
SELECT @SubmissionControlID = SubmissionControlID  from Inserted


  Begin

Insert Into errEDVisitOriginal (EDVisitId, SubmissionControlID)

VALUES (@EDVisitId, @SubmissionControlID )



End

Thanks for all the suggestions. 感谢所有的建议。 I abandoned the idea of a trigger. 我放弃了扳机的想法。 Instead I simply insert the new records from the first table into the second one. 相反,我只是简单地将第一个表中的新记录插入第二个表中。 See below. 见下文。

Insert errEDVisitOriginal(EdVisitId, SubmissionControlID)
    Select EdVisitId,  SubmissionControlID 
    from errEDVisit where SubmissionControlID = @SubmissionControlID

you just need scope_identity() 您只需要scope_identity()

Select @EDVisitId = scope_identity() 选择@EDVisitId = scope_identity()

You can use SCOPE_IDENTITY to get the last inserted id from the first table put it into a variable then insert into the second table. 您可以使用SCOPE_IDENTITY从第一个表中获取最后插入的ID,然后将其放入变量中,然后插入第二个表中。

https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql https://docs.microsoft.com/zh-cn/sql/t-sql/functions/scope-identity-transact-sql

Though the decision to duplicate information intentionally is dubious, you are vastly over-thinking the code. 尽管有意复制信息的决定值得怀疑,但是您对代码的想法却过于宽泛。 Just: 只是:

if exists (select * from inserted)
insert dbo.errEDVisitOriginal (EDVisitId, SubmissionControlID)
select EDVisitId, SubmissionControlID from inserted;

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

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