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

SQL2000中如何将添加和删除数据放在一个触发器中,利用一个判断语句实现
这里创建了一个student表,
create table student 
(sno char(9)primary key,
 sname char(20)unique,
 sage smallint ,
 ssex varchar(2),
 sdept varchar(20)
)
表student1
create table student1
(sno char(9)primary key,
 sname char(20)unique,
 sage smallint ,
 ssex varchar(2),
 sdept varchar(20)
)

然后我在企业管理器中创建了关于studen表的两个触发器,即添加和删除数据的触发器,当从student表删除或者是增加数据的时候,student1表也执行相同的操作。
CREATE trigger delete_stu on dbo.student
for delete
as
begin
delete from student1
select * from deleted
end

CREATE trigger insert_stu on dbo.student
for insert
as
begin
insert into student1
select * from inserted
end

我的问题是如何将这两个写进同一触发器中,加上判断条件,进而实现操作

------解决方案--------------------
SQL code
if not exists(select 1 from deleted) --添加

if not exists(select 1 from inserted) --删除

------解决方案--------------------
看到#1的想起应该要加多判断
SQL code
CREATE trigger delete_stu on dbo.student
for delete,insert
as
begin
    if not exists(select 1 from deleted) --添加
    begin
        insert into student1 select * from inserted
        select * from inserted
    end
    if not exists(select 1 from inserted) --删除
    begin
        delete from student1 where studentid in (select studentid from deleted)
        select * from deleted
    end
end