How to insert data into two table, while one depends of primary key of other
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.
精彩评论