Sql-Server-2012

如何在帶有序列的sql server中創建自定義ID

  • January 1, 2020

如何創建具有自定義 ID 的表,例如 BK-0001001 和序列。對不起,我是數據庫新手。所有幫助將不勝感激,謝謝!

您可以在 SEQUENCE 和格式化 DEFAULT CONSTRAINT 之間混合使用:

CREATE SEQUENCE MySequence
AS int
START WITH 1
INCREMENT BY 1;
GO
CREATE TABLE MyTable
(
    MySeq varchar(20) CONSTRAINT [DF_MyTable_MySeq]
                      DEFAULT FORMAT((NEXT VALUE FOR MySequence), 'BK-000000#'),
    Foo   int,
    Bar   int,

    CONSTRAINT [PK_MyTable] PRIMARY KEY (MySeq)
);
GO
INSERT INTO MyTable (Foo, Bar) 
VALUES (1,2),(2,3),(3,4),(5,6);
GO
SELECT * FROM MyTable;
GO
MySeq | 福 | 酒吧
:--------- | --: | --:
BK-0000001 | 1 | 2
BK-0000002 | 2 | 3
BK-0000003 | 3 | 4
BK-0000004 | 5 | 6

db<>在這裡擺弄

引用自:https://dba.stackexchange.com/questions/222617