如何创建插入触发器?

时间:2015-11-09 05:07:51

标签: sql-server triggers

我想开发一个触发器,该触发器将被放置在营销列表表中,如果尝试插入时该人的年龄小于18,则该记录将在子表中插入记录。子表和市场营销列表表具有相同的字段。到目前为止我开始了。我该如何继续?

create table child_list
(
Id              int         primary key,
Name            varchar(20)         ,
Date_of_Birth   date                ,
Gender          char(1)             ,
Parish          varchar(20)         ,
Mobile          integer             ,
Mobile_Provider varchar(7)          ,
age             integer, 
age_cat varchar(20)

);

 create trigger insert_child
   on marketing_list
  for insert 
   as
   if age<18....

1 个答案:

答案 0 :(得分:-1)

假设您在子表上没有标识列,则以下是您的查询:

create table child_list
(
child_list_Id              int         primary key,
Name            varchar(20)         ,
Date_of_Birth   date                ,
Gender          char(1)             ,
Parish          varchar(20)         ,
Mobile          integer             ,
Mobile_Provider varchar(7)          ,
age             integer, 
age_cat varchar(20)
)
go

create table marketing_list
(
marketing_list_Id              int         primary key,
VName            varchar(20)         ,
Date_of_Birth   date                ,
Gender          char(1)             ,
Parish          varchar(20)         ,
Mobile          integer             ,
Mobile_Provider varchar(7)          ,
age             integer, 
age_cat varchar(20)
)
GO

CREATE TRIGGER TRG_InsertChildList
ON marketing_list
AFTER INSERT
AS
BEGIN
    DECLARE @AGE INT
    SET @AGE = (SELECT age FROM INSERTED)

    IF (@AGE < 18)
    BEGIN
        INSERT INTO child_list 
        SELECT
            marketing_list_Id 
            ,Name
            ,Date_of_Birth
            ,Gender
            ,Parish
            ,Mobile
            ,Mobile_Provider
            ,age
            ,age_cat
        FROM INSERTED
    END
END

INSERT INTO marketing_list VALUES (1,'Test','03-04-1994',1,'Parish','123','AT&T',16,'age_cat')