将SCOPE_IDENTITY工作在这种情况下? [英] Will SCOPE_IDENTITY Work in this Case?
问题描述
我有PK是自我递增键。我需要插入记录到数据库中,然后拿到PK回来,并用它在另一个插入。
I have PK that is self incrementing key. I need to insert the record into the database and then get that PK back and use it in another insert.
不过,我想这样做在一个事务中。那可能吗。我们的想法是,如果事情失败,任何更新/插入了我必须做的话,我可以回滚的一切,但我下,我需要做一个提交IM pression。
However I would like to do this in one transaction. Is that possible. The idea is that if something fails in any of the updates/inserts I have to do then I can rollback everything but I am under the impression that I need to do a commit.
我要做到这一点在ado.net在第一,但后来改,因为我想,也许这将解决这个问题的存储过程。
I was going to do it in ado.net at first but then switched to a stored procedure since I thought maybe that would get around this issue.
请问一个SP帮我在这种情况下?
Will a SP help me out in this case?
推荐答案
是的,SCOPE_IDENTITY会给你最新的插入的ID。作为一种替代方法,如果你使用SQL Server 2005 +,你可以使用的输出第。
Yes, scope_identity will give you the latest inserted id. As an alternative, if you're using sql server 2005+ you can use the output clause.
INSERT INTO [MyTable]([MyCol])
OUTPUT INSERTED.ID
SELECT [MyCol] FROM [MySourceTable];
这篇关于将SCOPE_IDENTITY工作在这种情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!