zoukankan      html  css  js  c++  java
  • SQL 数据库 触发器 、事务

    触发器类型有两种

    1、AFTER(FOR)触发器

    在动作执行之后触发(增删改执行完成后,触发器中的代码再执行),不能为视图指定for触发器,只能为表指定该触发器。

    2、instead of触发器

    可以理解为替代触发操作执行,写了这个之后,写的执行代码就没有用了,就被触发器的代码覆盖了

    同时DML 触发器使用 deleted 和 inserted 逻辑(概念)表。

     它们在结构上类似于定义了触发器的表,即对其尝试执行了用户操作的表。 在 deleted 和 inserted 表保存了可能会被用户更改的行的旧值或新值。

    ⑴对于INSERT 操作,inserted保留新增的记录,deleted无记录

    ⑵对于DELETE 操作,inserted无记录,deleted保留被删除的记录

    ⑶对于UPDATE操作,inserted保留修改后的记录,deleted保留修改前的记录

    创建触发器

    create trigger Insert_Student --命名规范

    on student --针对于哪一个表

    for insert --针对于哪一个动作来触发

    as  

    触发执行的代码段

    go

    create trigger Delete_Info
    on info
    instead of delete
    as
        
    go
    
    
    create trigger Delete_Nation
    on nation 
    for delete
    as
        
    go
    View Code

    注:触发器常用的为级联删除:

    create trigger delete_student
    on student
    instead of delete
    as

    --如果要删除student表数据,那么需要级联删除
     declare @sno varchar(20);
     set @sno = sno from deleted --deleted固定格式,为删除执行所能删除的数据,并没有执行删除,而是把他们显示出来,在这获得要删除的数据的sno,然后先删除其他表中此sno的数据
     delete from score where sno = @sno;
     delete from student where sno = @sno;

    go

    create trigger Delete_Info
    on info
    instead of delete
    as
        declare @c varchar(20)
        select @c = code from deleted
        
        delete from work where infocode=@c
        delete from family where infocode=@c
        delete from info where code=@c
    go
    View Code

    事务

    数据库事务(Database Transaction) 是指作为单个逻辑工作单元执行的一系列操作。

    事务处理可以确保除非事务性单元内的所有操作都成功完成,否则不会永久更新面向数据的资源。

    begin tran (或transaction)  --开始事务

    commit                               --提交事务

    rollback                               --回滚事务

    事务特性:

    A原子性(atomicity)

    C一致性(consistency)

    I隔离性(isolation)

    D持久性(durability)

    @@ERROR 是判断事务有没有错的条件,无错时值为0,有错时值不为0。

    select * from cangku
    begin tran  --开始事务
    insert into cangku values(10008,'Boxster',70,10,1004)--没有错
    if @@ERROR >0
    begin--每一个执行语句后面写这句话是为了如果上一句有错误,
    --下面不管有多少执行语句,都不会执行,直接到tranrollback
        goto tranrollback--到最后一个执行语句的tranrollback
    end
    insert into cangku values(10002,'极光',66.50,10,1002)--主键约束
    if @@ERROR>0
        goto tranrollback
    insert into cangku values(10009,'XF',40,10,1003)--没有错
    if @@ERROR>0
    begin
        tranrollback:        --需要加上冒号
        rollback tran        --回滚所有事务中执行过的命令(撤销所有执行语句)
    end
    else
    begin
        commit tran   --提交事务(只有真正的走到了commit才是真正的更改数据库的数据)
    end
    View Code
  • 相关阅读:
    iOS中Zbar二维码扫描的使用
    SOJ 1135. 飞跃原野
    SOJ 1048.Inverso
    SOJ 1219. 新红黑树
    SOJ 1171. The Game of Efil
    SOJ 1180. Pasting Strings
    1215. 脱离地牢
    1317. Sudoku
    SOJ 1119. Factstone Benchmark
    soj 1099. Packing Passengers
  • 原文地址:https://www.cnblogs.com/shadow-wolf/p/6085329.html
Copyright © 2011-2022 走看看