Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 803
bmsqldev Avatar asked Nov 20 '15 08:11

bmsqldev


3 Answers

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.

like image 144
Krishnraj Rana Avatar answered Sep 29 '22 08:09

Krishnraj Rana


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
like image 28
Rahul Tripathi Avatar answered Sep 29 '22 07:09

Rahul Tripathi


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)
like image 45
Slasko Avatar answered Sep 29 '22 09:09

Slasko