Auto Increment a non-identity Column in sql-server

2019-02-13 14:47发布

问题:

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.

回答1:

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.



回答2:

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


回答3:

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)