美文网首页
mysql和SqlServer的触发器获取原行和新行数据

mysql和SqlServer的触发器获取原行和新行数据

作者: 哈哈新开张 | 来源:发表于2021-06-26 11:36 被阅读0次

Mysql

数据在old和 new
INSERT INTO `mes_dev`.`f_trigger_into`(`cate_name`, `created`) VALUES (new.id, unix_timestamp())

SqlServer

数据在inserted 和 deleted
例1 
DECLARE @tb_name nvarchar(50)
SET @tb_name= 'Department'

DECLARE @keys nvarchar(20);
SELECT @keys = iDepOrder from inserted;  --删除是数据在 deleted 里

BEGIN
    -- 新增
    IF EXISTS(SELECT 1 FROM inserted) AND NOT EXISTS(SELECT 1 FROM deleted)
        INSERT INTO sync_mes(type,tb_name,keys) VALUES (1,@tb_name,'add')
    -- 更新
    IF EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
        INSERT INTO sync_mes(type,tb_name,keys) VALUES (2,@tb_name,@keys)
    -- 删除
    IF NOT EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
        INSERT INTO sync_mes(type,tb_name,keys) VALUES (3,@tb_name,@keys)
 END

例2

DECLARE @tb_name nvarchar(50)
DECLARE @aKeys nvarchar(50)
DECLARE @uKeys nvarchar(50)
DECLARE @dKeys nvarchar(50)
SET @tb_name= 'Department'
BEGIN
    -- 新增   
    IF EXISTS(SELECT 1 FROM inserted) AND NOT EXISTS(SELECT 1 FROM deleted)
        INSERT INTO sync_mes(type,tb_name,keys) VALUES (1,@tb_name,(SELECT iDepOrder FROM inserted))
    -- 更新   
    IF EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
        INSERT INTO sync_mes(type,tb_name,keys) VALUES (2,@tb_name,(SELECT iDepOrder FROM inserted))
    -- 删除
    IF EXISTS(SELECT 1 FROM deleted) AND NOT EXISTS(SELECT 1 FROM inserted)
        INSERT INTO sync_mes(type,tb_name,keys) VALUES (3,@tb_name,(SELECT iDepOrder FROM deleted))
 END

相关文章

网友评论

      本文标题:mysql和SqlServer的触发器获取原行和新行数据

      本文链接:https://www.haomeiwen.com/subject/ujfzyltx.html