在软件实施过程中,也许会有这样的问题: 表中数据出现非预期的结果,此时不确定是程序问题,哪个程序,存储过程,触发器.. 或还是人为修改的结果,此时可以用触发器对特定的表字段做跟踪监视,记录每次新增,修改,删除此字段值的操作详细信息(含登录名,主机名,IP地址,执行的TSQL语句,程序名等等), 以利于问题的排查.

-- 建测试表
CREATE TABLE sto
    (
        id INT NOT NULL, -- 主键字段
        de DATETIME -- 被跟踪的字段
            CONSTRAINT pk_sto
            PRIMARY KEY (id)
    );

-- 建日志表
CREATE TABLE log_sto
    (
        logid      INT          NOT NULL IDENTITY(1, 1), -- 日志序号(日志主键)
        operate    VARCHAR(10),                          -- 操作类型 如Insert,Update,Delete.
        id         INT,                                  -- 原表ID(主键)
        old_de     DATETIME,                             -- de字段旧值
        new_de     DATETIME,                             -- de字段新值
        spid       INT          NOT NULL,                -- spid
        login_name VARCHAR(100),                         -- 登录名
        prog_name  VARCHAR(100),                         -- 程序名
        hostname   VARCHAR(100),                         -- 主机名
        ipaddress  VARCHAR(100),                         -- IP地址
        runsql     VARCHAR(4000),                        -- 执行的TSQL代码
        UDate      DATETIME -- 操作日期时间
            CONSTRAINT pk_logsto
            PRIMARY KEY (logid)
    );
GO

-- 建跟踪触发器
CREATE TRIGGER tr_sto
ON sto
AFTER UPDATE, INSERT, DELETE
AS
    BEGIN
        DECLARE @di TABLE
            (
                et VARCHAR(200),
                pt VARCHAR(200),
                ei VARCHAR(MAX)
            );
        INSERT INTO @di
        EXEC ('dbcc inputbuffer(@@spid)');

DECLARE @op VARCHAR(10);
        SELECT
            @op = CASE WHEN EXISTS ( SELECT 1 FROM inserted ) AND EXISTS (SELECT 1 FROM deleted)
                            THEN 'Update'
                       WHEN EXISTS ( SELECT 1 FROM inserted ) AND NOT EXISTS (SELECT 1 FROM deleted)
                            THEN 'Insert'
                       WHEN NOT EXISTS(SELECT 1 FROM inserted ) AND EXISTS (SELECT 1 FROM deleted)
                          THEN 'Delete'
                  END;

IF @op IN (
                      'Update', 'Insert'
                  )
            BEGIN
                INSERT INTO log_sto
                    (
                        operate,
                        id,
                        old_de,
                        new_de,
                        spid,
                        login_name,
                        prog_name,
                        hostname,
                        ipaddress,
                        runsql,
                        UDate
                    )
                            SELECT
                                @op,
                                n.id,
                                o.de,
                                n.de,
                                @@spid,
                                (
                                    SELECT
                                        login_name
                                    FROM
                                        sys.dm_exec_sessions
                                    WHERE
                                        session_id = @@spid
                                ),
                                (
                                    SELECT
                                        program_name
                                    FROM
                                        sys.dm_exec_sessions
                                    WHERE
                                        session_id = @@spid
                                ),
                                (
                                    SELECT
                                        hostname
                                    FROM
                                        sys.sysprocesses
                                    WHERE
                                        spid = @@spid
                                ),
                                (
                                    SELECT
                                        client_net_address
                                    FROM
                                        sys.dm_exec_connections
                                    WHERE
                                        session_id = @@spid
                                ),
                                (
                                    SELECT TOP 1
                                        ISNULL(ei, '')
                                    FROM
                                        @di
                                ),
                                GETDATE()
                            FROM
                                inserted n
                                LEFT JOIN
                                    deleted o
                                        ON o.id = n.id;
            END;
        ELSE
            BEGIN
                INSERT INTO log_sto
                    (
                        operate,
                        id,
                        old_de,
                        new_de,
                        spid,
                        login_name,
                        prog_name,
                        hostname,
                        ipaddress,
                        runsql,
                        UDate
                    )
                            SELECT
                                @op,
                                o.id,
                                o.de,
                                NULL,
                                @@spid,
                                (
                                    SELECT
                                        login_name
                                    FROM
                                        sys.dm_exec_sessions
                                    WHERE
                                        session_id = @@spid
                                ),
                                (
                                    SELECT
                                        program_name
                                    FROM
                                        sys.dm_exec_sessions
                                    WHERE
                                        session_id = @@spid
                                ),
                                (
                                    SELECT
                                        hostname
                                    FROM
                                        sys.sysprocesses
                                    WHERE
                                        spid = @@spid
                                ),
                                (
                                    SELECT
                                        client_net_address
                                    FROM
                                        sys.dm_exec_connections
                                    WHERE
                                        session_id = @@spid
                                ),
                                (
                                    SELECT TOP 1
                                        ISNULL(ei, '')
                                    FROM
                                        @di
                                ),
                                GETDATE()
                            FROM
                                deleted o;
            END;
    END;
GO

--> 测试DML操作

-- 操作1
INSERT INTO sto
    (
        id,
        de
    )
VALUES
    (
        1, '2012-01-01 05:06:07'
    );
GO

-- 操作2
INSERT INTO sto
    (
        id,
        de
    )
VALUES
    (
        2, '2012-01-01 06:06:07'
    );
GO

-- 操作3
UPDATE
    sto
SET
    de = getdate()
WHERE
    id = 2;
GO

-- 操作4
UPDATE
    sto
SET
    de = getdate()
WHERE
    id = 1;
GO

-- 操作5
INSERT INTO sto
    (
        id,
        de
    )
VALUES
    (
        5, '2012-01-01 15:26:37'
    );
GO

-- 操作6
DELETE sto
WHERE
    id = 2;
GO

MSSQL记录表字段数据变化的相关SQl的更多相关文章

  1. ms_sql 触发器记录表字段数据变化的日志 -针对一张表操作

    create table sto (id int not null, -- 主键字段 de datetime -- 被跟踪的字段 constraint pk_sto primary key(id)) ...

  2. resultset 对象获取行字段数据时报:java.sql.SQLException: Column 'id' not found.

    resultset 对象获取行字段数据时报:java.sql.SQLException: Column 'id' not found. 代码: String sql="SELECT d.co ...

  3. 触发器记录表某一个字段数据变化的日志 包括插入insert 修改update 删除delete 操作

    本文参考:http://www.cnblogs.com/lyhabc/articles/3236985.html ,),  ),               ),           ),       ...

  4. Entity Framework使用EntityState和Attach来保存数据变化以及更新实体的个别字段

    在使用Entity Framework作为ORM来存取数据的过程中,最常规的操作就是对数据对象的更新.本文将会包含如何Attach Entity到一个数据Context中,以及如何使用EntitySt ...

  5. Sql Server 添加、更新、查询表注释、字段注释相关sql

    /*******************字段添加注释*********************/ if not exists (SELECT C.value AS column_description ...

  6. 小程序的数据监听 用法和vue中的watch一样====使用通配符监听所有自数据字段的变化

    使用通配符监听所有自数据字段的变化

  7. mssql与mysql 数据迁移

    概要: mssql向mysql迁移的实例,所要用到的工具bcp和load data local infile. 由于订单记录的数据是存放在mssql服务器上的,而项目需求把数据迁移到mysql ser ...

  8. MSSQL批量写入数据方案

    近来有一个项目Feature需要有批量写入数据的场景,正巧整理资料发现自己以前也类似实现的项目,在重构的同时把相关资料做了一个简单的梳理,方便大家参考. 循环写入(简单粗暴,毕业设计就这样干的)(不推 ...

  9. Adapter数据变化改变现有View的实现原理及案例

    首先说说Adapter详细的类的继承关系.例如以下图 Adapte为接口它的实现类的对象作为AdapterView和View的桥梁,Adapter是装载了View(比方ListView和girdVie ...

随机推荐

  1. 【问题篇四】SpringBoot的properties文件不能自动提示解决方法(1)

    一.Eclipse 解决方法:Eclipse中安装Spring Tools Suite(STS). 这里采用离线安装的方式. 1. 官网:https://spring.io/tools3/sts/al ...

  2. (translation.E004) You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting.

    django3.0开始LANGUAGE_CODE前面必须配相应的LANGUAGES配置如下: from django.utils.translation import gettext_lazy as ...

  3. [LeetCode] 63. Unique Paths II 不同的路径之二

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The ...

  4. Ubuntu16LTS使用笔记(Server版)

    环境测试:Ubuntu Server 16.04.06 x64 虚拟机 以下均需要root权限,请sudo 或 su root 解决只有先启动Windows再重启到Linux才能使用usb网卡的问题: ...

  5. 从GopherChina 2019看当前的go语言

    GopherChina 2019大会4月底刚刚结束,大会上使用的PPT也放了出来(大会情况及PPT在https://mp.weixin.qq.com/s/_oVpIcBMVIKVzQn6YrkAJw) ...

  6. 分布式事物解决方案-TCC

    分布式框架下,如何保证事物一致性一直是一个热门话题.当然事物一致性解决方案有很多种(请参考:分布式事物一致性设计思路),我们今天主要介绍TCC方案解决的思路.以下是参与设计讨论的一种解决思路,大家有问 ...

  7. swagger Unable to render this definition

    Unable to render this definition The provided definition does not specify a valid version field. Ple ...

  8. Kubernetes 学习(十)Kubernetes 容器持久化存储

    0. 前言 最近在学习张磊老师的 深入剖析Kubernetes 系列课程,最近学到了 Kubernetes 容器持久化存储部分 现对这一部分的相关学习和体会做一下整理,内容参考 深入剖析Kuberne ...

  9. MySQL主键与索引的区别和联系

    MySQL主键与索引的区别和联系   关系数据库依赖于主键,它是数据库物理模式的基石.主键在物理层面上只有两个用途: 惟一地标识一行. 作为一个可以被外键有效引用的对象. 索引是一种特殊的文件(Inn ...

  10. Javascript Object常用方法总结

    Object.keys方法 Object.keys方法是JavaScript中用于遍历对象属性的一个方法 .它传入的参数是一个对象,返回的是一个数组,数组中包含的是该对象所有的属性名. 如: var ...