开发者

How to insert data into two table, while one depends of primary key of other

开发者 https://www.devze.com 2023-03-18 09:11 出处:网络
I\'m no expert at SQL, just know some nesseary basics, but I need to refactor my LINQ code into SPROCs for better perfomance andI have this scenario.

I'm no expert at SQL, just know some nesseary basics, but I need to refactor my LINQ code into SPROCs for better perfomance andI have this scenario. I have Two tables Threads and Posts.

While I'm creating Thread I also need to create post. It's one-to-many relationship (one Thread may have many posts). But while creating thread I have no way of know what ID thread will have becaause it's autogenerated Identity.

I thought I cloud simply first create thread and later Select last added thread, but How can I be sure it will be exactly the开发者_StackOverflow社区 thread I want ?


SELECT SCOPE_IDENTITY()

Read the following article @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record for a detailed explanation.


You can call SCOPE_IDENTITY() after your first INSERT. It will get the last Identity value generated. See http://msdn.microsoft.com/en-us/library/ms190315.aspx for more details.


Why can't you use trigger. Once you create the thread in the insert trigger you can create a post entry.

0

精彩评论

暂无评论...
验证码 换一张
取 消