I see two options:
(1) if your table that you're inserting data into has a DATE
or DATETIME
column that has the "right" year in it, you could simply add a persisted, computed column to your table - something like:
ALTER TABLE dbo.YourTable
ADD PKID AS RIGHT(CAST(YEAR(DateColumn) AS CHAR(4)), 2) + '-' +
RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED
Assuming that ID
is an INT IDENTITY
column that autogenerates sequential numbers, and you want to call your new column PKID
(change as needed).
Since this is a persisted computed column, it's computed once - when the row is inserted - and it can be indexed and used as primary key.
(2) If you don't have anything like a date column in your table, then the only option would be to have a AFTER INSERT
trigger on that table that does something like this (again: assuming you have a column ID INT IDENTITY
to provide the auto-incremented numbers):
CREATE TRIGGER trgInsert ON dbo.YourTable
AFTER INSERT
AS
BEGIN
DECLARE @YearPrefix CHAR(2)
SET @YearPrefix = RIGHT(CAST(YEAR(GETDATE()) AS CHAR(4)), 2)
UPDATE dbo.YourTable
SET OtherID = @YearPrefix + '-' + RIGHT('00000' + CAST(i.EmployeeID AS VARCHAR(5)), 5)
FROM INSERTED i
WHERE dbo.YourTable.EmployeeID = i.EmployeeID
END
And of course, first you need to add this new PKID
column to your table, too, so that the trigger can store values in it :-)
ALTER TABLE dbo.YourTable
ADD PKID VARCHAR(10) NOT NULL DEFAULT ('X') -- needs to be NOT NULL for Primary Key