The easiest solution based on an IDENTITY
column is to use a computed column - like this:
ALTER TABLE dbo.tbl01
ADD cust_num AS 'VIP' + RIGHT('000000' + CAST(pkid AS VARCHAR(6)), 6) PERSISTED;
Now, every time you insert a row into tbl01
without specifying values for pkid
or cust_num
:
INSERT INTO dbo.tbl01 (Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically increase your pkid
value, and cust_num
will contain values like VIP000001
, VIP000002
,...... and so on - automatically, safely, reliably, no duplicates.
UPDATE
Since you can't change your table definition, you will most likely need to use an AFTER INSERT
trigger - something like this:
CREATE TRIGGER trgTbl01AddCustNum
AFTER INSERT
ON dbo.tbl01
AS
BEGIN
UPDATE tbl01
SET cust_num = 'VIP' + RIGHT('000000' + CAST(pkid AS VARCHAR(6)), 6)
FROM tbl01
INNER JOIN Inserted i ON i.pkid = tbl01.pkid;
END;