日期:2014-05-18  浏览次数:20714 次

一个关于“触发器”的问题
我有两个表:
表1:exam_QuestionName
字段:QuestionCode TypeCode QuestionName QuestionNum(int) 

表2:exam_QuestionType
字段:TypeCode SubjectCode TypeName QuestionNum(int) 

要求:1.表1的QuestionNum字段值+1的时候,表2的QuestionNum也+1
  2.表1的QuestionNum字段值-1的时候,表2的QuestionNum也-1
  3.在SQLSever2000中实现
请大家帮帮我,谢谢!

------解决方案--------------------
大体写了一个,我也是半学习半用,接触触发器比较少,经测试有效。
SQL code

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

-- =============================================
-- Author:        brallow
-- Create date: 2008-10-17
-- Description:    Trigger Example For CSDN
-- =============================================
CREATE TRIGGER  [QUAutoCalc]
   ON  [dbo].[exam_QuestionName]
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Declare @eQuestionCode as varchar(10);
        Declare @eTypeCode as varchar(10);
    Declare @eQuestionNum as int;  
    --处理删除的数据
    select 
    @eQuestionCode= QuestionCode,
    @eTypeCode = TypeCode,
    @eQuestionNum=QuestionNum 
    from Deleted;
    if(@eQuestionCode is not Null and @eTypeCode is not Null)
        begin
        update exam_QuestionType
        set QuestionNum = QuestionNum - @eQuestionNum
        where TypeCode = @eTypeCode;
    end
    --清空数据
    set @eQuestionCode = Null;
    set @eTypeCode = Null;
    set @eQuestionNum = Null;
    --处理插入的数据    
    select 
    @eQuestionCode= QuestionCode,
    @eTypeCode = TypeCode,
    @eQuestionNum=QuestionNum 
    from Inserted;
    if(@eQuestionCode is not Null and @eTypeCode is not Null)
        begin
        update exam_QuestionType
        set QuestionNum = QuestionNum + @eQuestionNum
        where TypeCode = @eTypeCode;
    end
END