In SQL Server how do I generate an auto-increment primary key ID that consists of year , a special char and a sequential series no.?

后端 未结 2 974
星月不相逢
星月不相逢 2020-11-30 15:09

I am encountering this kind of advance SQL coding task like generating an auto-increment primary key ID that consists of a year, a special char and a sequential seri

2条回答
  •  有刺的猬
    2020-11-30 15:20

    Here is a complete solution. Please note that it's exactly the same as the duplicate I've marked - Database scheme, autoincrement - Just different details.

    CREATE TABLE [dbo].[STUDENT]
    (
        [ID] int identity(1,1) PRIMARY KEY,
        [Stud_LName] [varchar](100) NOT NULL,
        [Stud_FName] [varchar](100) NOT NULL,
        [Stud_MName] [varchar](100) NOT NULL
    )
    GO
    
    CREATE FUNCTION dbo.GetSudentId
    (
        @id int
    )
    RETURNS varchar(10)
    AS
    BEGIN
        RETURN Concat(Year(Getdate()), '-', RIGHT(Concat('0000', (SELECT COUNT(*) FROM STUDENT WHERE id < @Id)), 6))
    END
    GO
    
    ALTER TABLE [dbo].[STUDENT]
        ADD Stud_ID AS (dbo.GetSudentId(Id))
    GO
    

    Please note that the primary key of the table must still be the identity column (as shown in the script) since the computed column can't be the primary key.

提交回复
热议问题