加入收藏 | 设为首页 | 会员中心 | 我要投稿 威海站长网 (https://www.0631zz.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQL:实时更新的时间戳-触发器和on update

发布时间:2022-10-16 22:01:15 所属栏目:MsSql教程 来源:转载
导读: 业务需求精确到毫秒的数据最新更新时间做判断。
方案一:提供精确到毫秒的整数型时间戳
SELECT (unix_timestamp(current_timestamp(3))*1000);
alter table tb_workorderinfo add column L

业务需求精确到毫秒的数据最新更新时间做判断。

方案一:提供精确到毫秒的整数型时间戳

SELECT (unix_timestamp(current_timestamp(3))*1000);
alter table tb_workorderinfo add column LastUpdateTimeStamp timestamp(3) not null default (unix_timestamp(current_timestamp(3))*1000) comment '最近更新时间',
    add key `NON-LastUpdateTimeStamp`(LastUpdateTimeStamp);

试图通过on update 函数对字段进行实时更新,但是失败,选择用触发器对时间戳进行更新:


delimiter $$
CREATE TRIGGER `LastUpdateTimeStamp` BEFORE UPDATE ON `tb_workorderinfo_test` FOR EACH ROW
    begin
         set new.LastUpdateTimeStamp = (unix_timestamp(current_timestamp(3))*1000) ;
    end
$$

过程中出现报错两次:

1、[HY000][1442] Can't update table 'tb_workorderinfo_test' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

错误写法:不应该在更新同一张表时使用update语句,直接使用set和new old就可以了


CREATE TRIGGER `LastUpdateTimeStamp` AFTER UPDATE ON `tb_workorderinfo_test` FOR EACH ROW
                        begin
                            update tb_workorderinfo_test set LastUpdateTimeStamp = (unix_timestamp(current_timestamp(3))*1000) where id = old.id;
                        end

2、[HY000][1362] Updating of NEW row is not allowed in after trigger

错误写法:不应该使用after update,更改为before update ,after 不支持更新操作

方案一成功,但是基于尽量少使用触发器的原则,考虑方案二。

方案二:提供精确到毫秒的时间格式进行判断

alter table tb_workorderinfo add column LastUpdateTimeStamp timestamp(3) not null default current_timestamp(3)
    on update current_timestamp(3) comment '最近更新时间',
    add key `NON-LastUpdateTimeStamp`(LastUpdateTimeStamp);

使用 on update 方式实现字段针对表更新的实时更新,因为on update 不支持更新非时间类型字段Mssq触发器,因此使用‘YYYY-MM-DD HH:mm:ss.fff’格式。

ps:

触发器:

drop trigger LastUpdateTimeStamp;
show triggers;

(编辑:威海站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!