SQL Server 如何让两列自动递增?

发布于 2024-09-16 18:47:16 字数 100 浏览 3 评论 0原文

我的 SQL Server 数据库表中有两列,我希望在添加新字段时自动增量。但是,Managment Studio 不允许我将两列设置为 IDENTITY。还有其他方法可以做到这一点吗?

I have two columns in a table of a SQL server DB that I would like to autoincrement when new fields are added. However, Managment Studio wont allow me to set two columns to IDENTITY. Is there some other way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

時窥 2024-09-23 18:47:16

您可以将第二个字段设置为基于第一个字段的计算字段。

或者创建一个 INSERT 触发器,然后以编程方式生成第二个值。

You could make the second field a calculated field based on the first.

Or make an INSERT trigger than programatically generates the value for the second.

染墨丶若流云 2024-09-23 18:47:16

如果您希望第二列基本上成为第一列的镜像:

ALTER TABLE dbo.myTable ADD
   foo  AS [rowid]
GO

如果您希望它对其应用一些数学公式以实现某种偏移:

ALTER TABLE dbo.myTable ADD
    foo  AS ([rowid]+1) * 7 --or whatever you like.
GO

If you wanted the 2nd column to basically be a mirror of the first:

ALTER TABLE dbo.myTable ADD
   foo  AS [rowid]
GO

If you wanted it to apply some math formula to it to achieve some kind of offset:

ALTER TABLE dbo.myTable ADD
    foo  AS ([rowid]+1) * 7 --or whatever you like.
GO
雪落纷纷 2024-09-23 18:47:16

每个表只能有一个自增字段。但是,您可以有一个基于自动增量字段的计算字段。或者,您可以有一个 int 字段,您可以在其中通过前端代码或触发器管理序列。您还可以在 SQL Server 中使用序列

CREATE SEQUENCE MySequence START WITH 100;

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

There can only be one auto increment field per table. But, you could have a calculated field based on the auto increment field. Or, you could have an int field where you manage the sequence by front end code or by a trigger. And also you could use a sequence in SQL Server.

CREATE SEQUENCE MySequence START WITH 100;

CREATE TABLE MyTable
(
    RealIdentity INT IDENTITY(1,1),
    RandomCol NVARCHAR(100),
    FakeIdentity INT DEFAULT NEXT VALUE FOR MySequence
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文