How to Get Last Created Entry's ID From Sql Da

2020-04-16 04:46发布

问题:

I will explain problem with an example:

There is two table in my database, named entry, tags

There is a column named ID_ENTRY in both table. When I add a record to table, entry, I have to take the ID_ENTRY of last added record and add it to table, tags. How can I do it?

回答1:

Immediatly after executing the insert statement on first table, you should query @@IDENTITY doing "SELECT @@identity". That will retrieve the last autogenerated ID... and then just insert it on the second table.

If you are using triggers or something that inserts rows... this may be not work. Use Scope_Identity() instead of @@IDENTITY



回答2:

The only way to do this is with multiple statements. Using dynamic sql you can do this by separating each statement in your query string with a semi-colon:

"DECLARE @ID int;INSERT INTO [Entry] (...) VALUES ...; SELECT @ID = scope_identity();INSERT INTO [TAGS] (ID_ENTRY) VALUES (@ID);"

Make sure you put this in a transaction to protect against concurrency problems and keep it all atomic. You could also break that up into two separate queries to return the new ID value in the middle if you want; just make sure both queries are in the same transaction.

Also: you are using parameterized queries with your dynamic sql, right? If you're not, I'll personally come over there and smack you 10,000 times with a wet noodle until you repent of your insecure ways.



回答3:

I would probably do this with an INSERT trigger on the named entry table, if you have all of the data you need to push to the tags table available. If not, then you might want to consider using a stored procedure that creates both inside a transaction.

If you want to do it in code, you'll need to be more specific about how you are managing your data. Are you using DataAdapter, DataTables, LINQ, NHibernate, ...? Essentially, you need to wrap both inserts inside a transaction of some sort so that either inserts get executed or neither do, but the means to doing that depend on what technology you are using to interact with the database.



回答4:

If you use dynamic sql, why not use Linq to Entity Framework, now EF is the recommend data access technology from Microsoft (see this post Clarifying the message on L2S Futures from ADO.NET team blog), and if you do an insert with EF the last identity id will available for you automatically, I use it all the time it's easy.

Hope this helps!

Ray.