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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With