• MSSQL 触发器


    ---触发器练习
    
    --在SQL Server里面也就是对某一个表的一定的操作,触发某种条件,从而执行的一段程序
     CREATE TABLE Student 
     ( 
        SID INT PRIMARY KEY       --学号 
     ) 
    
     CREATE TABLE BorrowRecord
        (
          --学生借书记录表 
          BorrowRecord INT IDENTITY(1, 1) ,       --流水号   
          StudentID INT ,                    --学号 
          BorrowDate DATETIME ,                --借出时间 
          ReturnDAte DATETIME,                --归还时间 
           
          
        )
    --EXEC sp_rename 'student.sid', 'studentid', 'COLUMN'
    INSERT BorrowRecord VALUES(1,GETDATE(),GETDATE())
    INSERT BorrowRecord VALUES(1,GETDATE(),GETDATE())
    
    INSERT BorrowRecord VALUES(2,GETDATE(),GETDATE())
    
    INSERT BorrowRecord VALUES(3,GETDATE(),GETDATE())
    
    ------------Insert----------------------------
    if (object_id('tr_insert', 'TR') is not null)    
    drop trigger tr_insert
    go
    CREATE TRIGGER tr_insert
    ON BorrowRecord
    FOR insert
    as
    DECLARE @studentid INT;
    SELECT @studentid=studentid FROM INSERTED
    INSERT INTO student VALUES(@studentid) ;
    go
    INSERT BorrowRecord VALUES(11,GETDATE(),GETDATE())
    ----------------Update---------------------------
    if (object_id('truStudent', 'TR') is not null)    
    drop trigger truStudent
    go
    create TRIGGER truStudent 
        ON student --在Student表中创建触发器 
        FOR UPDATE --为什么事件触发
    AS
        IF UPDATE(studentid) 
            BEGIN
                UPDATE  BorrowRecord
                SET     StudentID = i.studentid
                FROM    BorrowRecord br ,
                        DELETED d ,
                        INSERTED i
                WHERE   br.StudentID = d.studentid
    
            END
    --实例
    UPDATE student SET studentid=2 WHERE studentid=7
    SELECT * FROM BorrowRecord
    SELECT * FROM student
    ----------------delete---------------------------
    if (object_id('deletri', 'TR') is not null)    
    drop trigger deletri
    go
    CREATE TRIGGER deletri
    ON student
    FOR DELETE
    AS 
    DELETE BorrowRecord FROM BorrowRecord br,DELETED d
    WHERE br.StudentID=d.studentid
    --实例
    DELETE FROM student WHERE studentid=7
    SELECT * FROM BorrowRecord
  • 相关阅读:
    Emqx启用Redis认证
    写在2021末
    如何让 Spring Security 「少管闲事」
    泛型就这么简单
    Spring Boot 对多线程支持提高程序执行效率
    Java桌面应用JavaFX01Hello World
    PostgreSQL实现Oracle merge into功能
    超大JSON文件解析方案(Java)
    记一次IDEA搭建Spring源码阅读环境
    Oracle转PostgreSQL之start with / connect by
  • 原文地址:https://www.cnblogs.com/wangyuelang0526/p/2582613.html
Copyright © 2020-2023  润新知