插入值与组合标识列

use*_*236 0 sql sql-server

Let's say I have this table with the identity column pkid, how can I generate the cust_num as VIP000000 + <pkid> when inserting a record like this?

pkid cust_name cust_num
1 Tom VIP0000001
2 May VIP0000002
10 John VIP0000010
CREATE TABLE [dbo].[tbl01]
(
    [pkid] [numeric](9, 0) IDENTITY(1,1) NOT NULL,
    [cust_name] [varchar](50) NOT NULL,
    [cust_num] [varchar](20) NOT NULL
) ON [PRIMARY]
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 5

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;
   
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)