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
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.