Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS SQL Auto Increment non Identity Column

I have a table with an auto incrementing identity/primary key column called ID.

CREATE TABLE Table1(

[ID] [bigint] IDENTITY(1,1) NOT NULL,

[TextContent] [nvarchar](450) NOT NULL,

[Version] [bigint] NOT NULL)

When I UPDATE [TextContent], I'd like [Version] to increment by one. The intent is to have a version for each row that increments anytime the row is updated.

Is there a reasonable way to do this within a single table? Something to do with computed column values and/or triggers perhaps?

I'm using MSSQL 2008 via Entity Framework.

Thanks for any info!

like image 571
Simon Ordo Avatar asked Nov 30 '25 02:11

Simon Ordo


1 Answers

Method 1

Try creating a TRIGGER

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

Method 2

Using Update Command

Increment the Column Value each time along with using update command as below

UPDATE Tab
   SET Version= Version + 1
 WHERE id = 1
like image 141
Heemanshu Bhalla Avatar answered Dec 03 '25 08:12

Heemanshu Bhalla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!