This is Regarding MSSQL auto increment feature and i have following table created

CREATE TABLE Order(
[order_id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NULL,
[original_order_id] [int] NOT NULL
)

In here i have a situation where i need to insert the auto generated value for original_id to original_order_id.

After googling few minutes following thing and it works fine for me

insert into Order values('Vegitable Order', IDENT_CURRENT('Order'))

I am using java application spring JDBC templates to execute the quires. can there be any issues? specially in multi threaded environment?

有帮助吗?

解决方案

Using IDENT_CURRENT is not a good idea. If there are concurrent transactions, the returned value might not be your last inserted id, but the last inserted id of another transaction!

Use the JDBC getGeneratedKey facility to retrieve the generated id of the first INSERT and use the retrieved value in the second INSERT, or use SCOPE_IDENTITY() in the second INSERT. With SCOPE_IDENTITY() be sure that you are executing both statements in the same transaction.

See also: How to get the insert ID in JDBC?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top