SQL Server - Create a custom auto-increment field

前端 未结 1 1519
余生分开走
余生分开走 2021-01-07 05:30

I am trying to produce a custom auto-increment functionality in sql. my custom auto-incerement ID should be like below...

S1501.001

\"S\" i

相关标签:
1条回答
  • 2021-01-07 06:13

    The best solution is to use

    • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
    • a computed, persisted column to convert that numeric value to the value you need

    So try this:

    CREATE TABLE dbo.tblCompany
      (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
       CompanyID AS 'S1501.' + RIGHT('000' + CAST(ID AS VARCHAR(3)), 3) PERSISTED,
       .... your other columns here....
      )
    

    Now, every time you insert a row into tblCompany without specifying values for ID or CompanyID:

    INSERT INTO dbo.tblCompany(Col1, Col2, ..., ColN)
    VALUES (Val1, Val2, ....., ValN)
    

    then SQL Server will automatically and safely increase your ID value, and CompanyID will contain values like S1501.001, S1501.002,...... and so on - automatically, safely, reliably, no duplicates.

    0 讨论(0)
提交回复
热议问题