简体   繁体   中英

I want to get the current date time every time I update or insert a row in SQL Server

I have a table s_phone in this table there is column s_update .

I want to get the current date time every time I update or insert into this table

getdate() or systime() or CURRENT_TIMESTAMP get the date time when insert only not when update

You can use TRIGGER The trigger will be automatically run when insert/update happen in the table.

For example:

create table tbl1
(
    col1 int primary key,
    col2 datetime
)
go
create trigger trg01
on tbl1
for insert, update
as 
begin
   update tbl1 
   set col2 = GETDATE()
   where col1 in (select col1 from inserted)
end   
go
insert into tbl1(col1) values (1);

Your question is confusing, first you said, "..i want to get current date time every time i update or insert into this table.." and on the last part of your question, you said, ".. get the date time when insert only not when update .."

But give this a try, why not set a default value on the column, example:

CREATE TABLE Hello
(
    ID INT,
    DATE DATETIME DEFAULT GETDATE()
)


INSERT INTO Hello (ID) VALUES (1)
INSERT INTO Hello (ID) VALUES (2)
INSERT INTO Hello (ID) VALUES (3)
INSERT INTO Hello (ID) VALUES (4)
getdate() or systime() or CURRENT_TIMESTAMP 

These will give you the current system date time. if you want on the insert, update event capture the date time use the trigger or yourself you can get the datetime and insert into required table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM