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

一个关于触发器中用case when 的问题
想写一个触发器,把一个表里符合不同条件的记录写入其他不同的表里面,看看能否用case when ,我把问题简化叙述如下:

表a,b,c,d结构相同,其中表a中已经有多条记录如下:
id name age
1 令狐冲 22
2 乔峰 33
3 张无忌 19
4 段誉 18
5 虚竹 21
6 郭靖 42

如下写成三个语句
create trigger xxx on a for insert as 
begin
insert into b select * from a where a.id = inserted.id and age <20 
insert into c select * from a where a.id = inserted.id and age >= 20 and age <30
insert into d select * from a where a.id = inserted.id and age >= 30
end
这样固然能够完成目标,但是我想简化成一个语句,简化如下:

create trigger xxx on a for insert as 
declare @age int
select @age = age from a
begin
insert into case when @age < 20 then b
  when @age >= 20 and @age < 30 then c
  else d end
select * from a
where a.id = inserted.id 
end

执行,提示错误【关键字 'case' 附近有语法错误。】

我的问题是:这个错误如何纠正?能简化成一个语句吗?
菜鸟第一次发问题,浅陋勿笑

------解决方案--------------------
用if....else...
另外,触发器没有考虑到多行的情况,还需修改
SQL code

create trigger xxx on a for insert as  
declare @age int
select @age = age from insertd a
begin
if @age < 20
begin
    insert into b
    select * from a
    where a.id = inserted.id  
end
else
begin
    if @age >= 20 and @age < 30 
    begin
        insert into c
        select * from a
        where a.id = inserted.id  
    end
    else
    begin
        insert into d
        select * from a
        where a.id = inserted.id  
    end
end
end

------解决方案--------------------
SQL code
create trigger xxx on t1 for insert as  
begin
    declare @age int
    select @age = age from inserted
    if @age<20
        insert into b select * from inserted
    else if (@age>20 and @age<30)
        insert into c select * from inserted
    else if @age>30
        insert into d select * from inserted
end

------解决方案--------------------
SQL code
create trigger xxx on a for insert as  
begin
insert into b select * from a where a.id = inserted.id and age <20  
insert into c select * from a where a.id = inserted.id and age >= 20 and age <30
insert into d select * from a where a.id = inserted.id and age >= 30
end

------解决方案--------------------
2楼的是有问题的,如果一次插入多条,age不同段,就会出现插错表的现象