I need to enter primary key in table as in below format
YYYY/MMM/NNNNNN
Where, YYYY is the current year, MMM is Month , and NNNNNN is a sequence no from 000001, 000002, 000003, .... 999999.
So my primary key will look like 2012/Oct/000001 or 2012/Oct/000010 ….
How can I generate this type of code..
I can get Year and Month from Getdate() function. But how can I manage sequence number on every insert. can you please give me logic for that?
By far the easiest way would be to let SQL Server handle the dishing out of consecutive numbers using an
INT IDENTITYcolumn – and then use a trigger to create that specific format that you need, in a separate column.So given this table:
you could use a trigger like this to compute the
ComputedPKfrom theID(autonumber, handled by SQL Server) and theSaleDateas the date column:This approach will not start at 1 for each month, however – but do you really need that? Isn’t a sequential number (even across months) good enough?
Update: of course, if you’re using SQL Server 2012 (you didn’t specify which version of SQL Server you’re using…) – you could use a
SEQUENCEobject to handle the consecutive numbering – and you could even reset that sequence to 1 again every start of a month ….