【问题标题】:How to set two columns in SQL Server database as auto increment int with increment seed 100?如何将 SQL Server 数据库中的两列设置为增量种子 100 的自动增量 int?
【发布时间】:2011-01-06 07:42:58
【问题描述】:

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

【问题讨论】:

  • 假设你的意思是在一个表中,你不能。更重要的是,您为什么要这样做?

标签: sql-server


【解决方案1】:

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

使用派生计算列进行模拟

如果两个“身份”列相互同步,或者第二个身份可以使用公式从第一个身份派生,则可能适用计算列,例如如果第二个identity 从实际的标识列偏移了一个常量:

ALTER TABLE MyTable ADD OtherIdentity AS RealIdentity + 100;

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

Computed Column derived off Identity SqlFiddle example here

使用独立序列

另一种选择是使用independent Sequence (Sql2012 and Later)

CREATE SEQUENCE MySequence START WITH 100;

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

Sequence SqlFiddle example here

【讨论】:

    【解决方案2】:

    就像 nonnb 所说,您只能将一列标记为身份。但是,如果两个标识列之间存在数学关系,则可以使用计算列。例如,如果第二个 id 等于第一个 id 加上 500,您可以使用:

    create table t1 (id1 int identity(1,100), id2 as id1 + 500)
    

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 2011-04-07
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 2021-01-07
      • 1970-01-01
      • 2011-03-08
      • 2014-06-08
      相关资源
      最近更新 更多