Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql when set default value getdate(), does it set value when run update statement?

Tags:

sql

t-sql

I know when you insert a value into db, it set that column value as current datetime, does it apply to it when you run a update statement?

e.g.

table schema:

Id, Name, CreatedDate(getdate())

when i insert into table id = 1 , name = 'john' it will set createdDate = current date

if i run an update statement

update table set name="john2" where id =1

Will it update the createdDate?

like image 743
Kiddo Avatar asked Aug 04 '26 21:08

Kiddo


2 Answers

No, a DEFAULT CONSTRAINT is only invoked on INSERT, and only when (a) combined with a NOT NULL constraint or (b) using DEFAULT VALUES. For an UPDATE, SQL Server is not going to look at your DEFAULT CONSTRAINT at all. Currently you need a trigger ( see How do I add a "last updated" column in a SQL Server 2008 R2 table? ), but there have been multiple requests for this functionality to be built in.

I've blogged about a way to trick SQL Server into doing this using temporal tables:

  • Maintaining LastModified Without Triggers

But this is full of caveats and limitations and was really only making light of multiple other similar posts:

like image 51
Aaron Bertrand Avatar answered Aug 07 '26 13:08

Aaron Bertrand


wow - hard to understand...

i think NO based on the clues.

if you insert a record with a NULL in a column, and that column has a default value defined, then the default value will be stored instead of null.

update will only update the columns specified in the statement.

UNLESS you have a trigger that does the special logic - in which case, you need to look at the trigger code to know the answer.

like image 37
Randy Avatar answered Aug 07 '26 12:08

Randy



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!