简体   繁体   中英

Auto Increment a non-identity Column in sql-server

We have Non- Identity Column in our Database Which have a specific value . We have a requirement as below,

Whenever a record insert into that column, value should be incremented by one.

how to handle this in sql server ?

Thanks for the help.

Well, you can use SEQUENCE statement introduced in SQL Server 2012 brings the method of generating IDs

To use it in insert statement, you need to first create sequence like this -

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  INTO dbo.Test1
        ( orderid ,
          custid ,
          empid
        )
        SELECT NEXT VALUE FOR dbo.Id_Sequence,
                @custid ,
                @empid

That's it.

Try creating a 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

SELECT MAX(MyColumn)+1 FROM MyTable

maybe add ISNULL for first run.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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