zoukankan      html  css  js  c++  java
  • 简单的触发器

    定义: 何为触发器?在SQL Server里面也就是对某一个表的一定的操作,触发某种条件,从而执行的一段程序。触发器是一个特殊的存储过程。 
    常见的触发器有三种:分别应用于Insert , Update , Delete 事件。 

    表一:news表

    CREATE TABLE [dbo].[news](
     [ID] [int] IDENTITY(1,1) NOT NULL,
     [title] [nvarchar](50) NULL,
     [contents] [nvarchar](50) NULL

    表二:newsdel记录被删除、被修改过的news信息

    CREATE TABLE [dbo].[newsdel](
     [ID] [int] IDENTITY(1,1) NOT NULL,
     [newsID] [int] NULL,
     [title] [nvarchar](50) NULL,
     [contents] [nvarchar](50) NULL

    触发器的基本语法:

    create trigger newsdeleted         -----创建触发器,名称可以自己随便叫
    On news                                     -----表名称,即操作的对象,可多个
    for Delete                                   -----事件,一般为Insert , Update , Delete 事件,可多选
    As 
    insert into newsdel(newsID,title,contents)               ---------------要执行的sql
    select ID,title,contents from Deleted                      

    注意:inserted临时表,表示新插入的信息,也包括新加的和修改后的新信息;

               deleted临时表,表示被删除的信息,也包括被修改前的信息

    1>把删除的news信息保存在newsdel表中,我们需要一个delete触发器:

    create trigger newsdeleted 
    On news 
    for Delete 
    As 
    insert into newsdel(newsID,title,contents) 
    select ID,title,contents from Deleted

    2>把修改前的news信息保存在newsdel表中,我们需要一个update触发器:

    create trigger newsupdated
    On news 
    for update 
     As 
    insert into newsdel(newsID,title,contents) 
    select ID,title,contents from Deleted


    //成功一定有方法,失败一定有原因。
  • 相关阅读:
    javascript如何判断一个对象是不是数组
    Socket 通讯
    XML 文件解析
    iOS 钥匙串 指纹识别 get和Post请求的区别
    MOS X 下Apache服务器配置,及日志读取
    iOS中图片动画的三种模式及基本的代码实现
    UI中 frame 与 transform的用法与总结
    Xcode 缓存 帮助文档 隐藏文件夹显示方法
    NSDate用法整理总结
    iOS沙盒机制的基本操作总结
  • 原文地址:https://www.cnblogs.com/webapi/p/2425939.html
Copyright © 2011-2022 走看看