How can I have two columns in SQL Server auto increment?

两盒软妹~` 提交于 2019-12-19 04:37:06

问题


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?


回答1:


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.




回答2:


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



回答3:


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
);


来源:https://stackoverflow.com/questions/3622627/how-can-i-have-two-columns-in-sql-server-auto-increment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!