简体   繁体   English

自动增加sql-server中的非标识列

[英]Auto Increment a non-identity Column in sql-server

We have Non- Identity Column in our Database Which have a specific value . 我们的数据库中有非Identity Column ,它们具有特定值。 We have a requirement as below, 我们有如下要求,

Whenever a record insert into that column, value should be incremented by one. 每当记录insert该列时,值应加1。

how to handle this in sql server ? 如何在sql server处理这个?

Thanks for the help. 谢谢您的帮助。

Well, you can use SEQUENCE statement introduced in SQL Server 2012 brings the method of generating IDs 好吧,你可以使用SQL Server 2012中引入的SEQUENCE语句带来生成ID的方法

To use it in insert statement, you need to first create sequence like this - 要在insert语句中使用它,您需要首先创建这样的序列 -

CREATE SEQUENCE dbo.Id_Sequence
    AS INT
    START WITH 1
    INCREMENT BY 1
    MINVALUE 0
    NO MAXVALUE

Now use it in your insert statement like this - 现在在你的insert语句中使用它 -

INSERT  INTO dbo.Test1
        ( orderid ,
          custid ,
          empid
        )
        SELECT NEXT VALUE FOR dbo.Id_Sequence,
                @custid ,
                @empid

That's it. 而已。

Try creating a TRIGGER 尝试创建TRIGGER

CREATE TRIGGER incrementValue
ON Test
FOR Insert
AS 
   Update Test  
   set columnvalue = columnvalue +1 
   where id in (select id from inserted)
GO

You can load the max value of the table and add +1 您可以加载表格的最大值并添加+1

SELECT MAX(MyColumn)+1 FROM MyTable

maybe add ISNULL for first run. 也许首次运行时添加ISNULL。

ISNULL((SELECT MAX(MyColumn)+1 FROM MyTable),0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM