SQL Server : use generated ID column value in another column [duplicate]

8fsztsew  于 2023-10-15  发布在  SQL Server
关注(0)|答案(1)|浏览(137)

This question already has answers here:

Create an auto incrementing alpha numeric primary key (1 answer)
Dynamic Default value while defining column definition (1 answer)

Closed 16 days ago.

Small reproducible query:

INSERT INTO records (serial_number, cust_name) 
VALUES ('REGION_CODE' + IDENT_CURRENT('records'), 'CUST_NAME') 
OUTPUT Inserted.serial_number

The idea is to generate a serial number based on the autogenerated integer ID and REGION_CODE prefix stored separately which is different for each region which is looked up in the application code.

The problem is sometimes, there is a rare occurrence there are two queries which differ in seconds causing IDENT_CURRENT('records') to return the same ID. This causes two rows to have duplicated ID's. We have multiple transactions every second, but this duplicate ID incident only happens about once a month, so I am guessing there are some anomalies.

Is there a way to ensure that the serial_number generated will never be the same and relate to the current auto generated id?

We have tried using SCOPE_IDENTITY() , but it seems to return lagged id.

Triggers won't work since we need to return the inserted serial_number

xxb16uws

xxb16uws1#

Why don't you just make this a computed column inside SQL Server?

Then you don't need to insert values into it at all - it will automagically show the appropriate "constructed" ID for you.

ALTER TABLE dbo.Records
    ADD Serial_Number AS CONCAT(Region_Code, RecordsId);

I guessed that your primary key column is called RecordsId - if it's something else, adapt as needed.

This will concatenate together the contents of your Region_Code and your RecordsId column and surface that as a new column Serial_Number in your Records table.

Any time you insert a value like this:

INSERT INTO records (cust_name) 
VALUES ('CUST_NAME');

the primary key (auto-generated by the IDENTITY spec) will be incremented, and the Serial_Number column will be automagically set to the expected value. No more need to fiddle with getting the ID value from the INSERT and inserting the value for Serial_Number yourself - let SQL Server take care of that for you

相关问题