且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 SQL Server 数据库中的两列设置为增量种子为 100 的自动增量 int?

更新时间:2023-09-22 20:06:52

每个表只能有一个标识列,但是,有一些想法和解决方法 此处

You can only have one identity column per table, however, there are some ideas and workarounds here

使用派生计算列进行模拟

如果两个身份"列彼此同步,或者可以使用公式从第一个身份派生出第二个身份,那么计算列可能适用,例如如果第二个 identity 与实际 Identity 列的常量偏移:

If both "identity" columns are synchronized with each other, or the second identity can be derived from the first using a formula, then a Computed Column might be applicable, e.g. if the second identity is offset by a constant from the actual Identity column:

ALTER TABLE MyTable ADD OtherIdentity AS RealIdentity + 100;

其中 RealIdentity 是实际/原始 IDENTITY 列.

Where RealIdentity is the actual / original IDENTITY column.

计算列派生自 Identity SqlFiddle 示例

使用独立序列

另一种选择是使用 独立序列(Sql2012 及更高版本)

CREATE SEQUENCE MySequence START WITH 100;

CREATE TABLE MyTable
(
    RealIdentity INT IDENTITY(1,1),
    RandomCol NVARCHAR(100),
    FakeIdentity INT DEFAULT NEXT VALUE FOR MySequence
);

此处为 SqlFiddle 序列示例