0

开发一个触发器,该触发器将放置在营销列表表中,一旦尝试插入,该触发器将在此人的年龄小于 18 岁时将一条记录插入到子表中。

请参阅下面的代码:

Create Trigger on_insert_marketing_list
On marketing_list for insert
As
BEGIN
        Declare @Name varchar (100)
        Declare @Dob date
        Declare @Gender char(1)
        Declare @Parish VARCHAR(50)
        Declare @Mobile varchar(50)
        Declare @Provider varchar(50)
        Declare @age int

        Select @age = datediff(year,@dob,getdate())from inserted

        If (@age) < 18      
        BEGIN
        Insert Into Childlist values(@Name,@Dob,@Gender,@Parish,@Mobile,@Provider)
        END

End

insert into marketing_list (Name, Dob, Gender,  Parish,  Mobile, Mobile_Provider) values
('Kendrick Lamar', '3/4/2005','M','Kingston', '18764532345','LIME')
4

2 回答 2

0

只是想发布我计算某人年龄的函数:

create function [dbo].[CalculateAge] ( @p_BirthDate date, @p_ReferenceDate date )
returns int as
begin

  return DateDiff( Year, @p_BirthDate, @p_ReferenceDate ) - 
         ( Case When DateAdd( Year, DateDiff( Year, @p_BirthDate, @p_ReferenceDate ), @p_BirthDate ) > @p_ReferenceDate Then 1 Else 0 End )

end
于 2012-11-06T17:54:15.553 回答
0

而不是有ChildsList表,为什么不是这个视图:

CREATE VIEW ChildsList
AS
   SELECT
       Name,
       DOB,
        Gender,
       Parish,
       Mobile,
       Mobile_Provider
    FROM
        marketing_list
    WHERE
       DOB >= DATEADD(year,-18,CURRENT_TIMESTAMP)

这是 a) 始终是最新的,并且 b) 不尝试直接计算他们的年龄,因此不必摆弄正确的计算。


如果您仍然想要触发器,请执行以下操作:

Insert Into Childlist 
select Name,Dob,Gender,Parish,Mobile,Mobile_Provider
from
    inserted where DOB >= DATEADD(year,-18,CURRENT_TIMESTAMP)

但正如我所说,一旦日期更改,它就会立即过时。

这将正确地将一行插入ChildList表中,以进行如下插入:

INSERT INTO marketing_list (Name, Dob, Gender,  Parish,  Mobile, Mobile_Provider) values
('Kendrick Lamar', '20050403','M','Kingston', '18764532345','LIME'),
('Phillip Lamar', '198550403','M','Elsewhere', '18764532346','ORANGE'),
于 2012-11-06T15:49:33.860 回答