SQL server触发器中 update insert delete 分别给写个例子以及解释下例子的作用和意思被, 万分感谢!!!!
主要想知道下各个语句的书写规范。
INSERT:
表1 (ID,NAME)
表2 (ID,NAME)
当用户插入表1数据后,表2也被插入相同的数据
CREATE TRIGGER TRI1
ON 表1
FOR INSERT
AS
BEGIN
INSERT INTO 表2 SELECT * FROM INSERTED
END
GO
DELETE:
表1 (ID,NAME)
表2 (ID,AGE,GENDER)
当用户删除表1某条ID的数据后,表2相应ID的数据也被删除
CREATE TRIGGER TRI2
ON 表1
FOR DELETE
AS
BEGIN
DECLARE @id INT
SELECT @id FROM DELETED
DELETE 表2
WHERE ID = @id
END
GO
UPDATE:
表1 (ID,NAME)
表2 (ID,NAME)
当用户更改表1 NAME列数据后,表2相应ID的数据也同时更新
CREATE TRIGGER TRI3
ON 表1
FOR UPDATE
AS
IF UPDATE(NAME)
BEGIN
UPDATE 表2
SET A.NAME = B.NAME
FROM 表2 A, INSERTED B
WHERE A.ID = B.ID
END
GO -------------------------------------------------
insert 触发器示例
create trigger tri_insert
on student
for insert
as
declare @student_id char(10)
select @student_id=s.student_id from
student s inner join inserted i
on s.student_id=i.student_id
if @student_id='0000000001'
begin
raiserror('不能插入1的学号!',16,8)
rollback tran
end
go
update触发器示例
create trigger tri_update
on student
for update
as
if update(student_id)
begin
raiserror('学号不能修改!',16,8)
rollback tran
end
go
delete触发器示例
create trigger tri_delete
on student
for delete
as
declare @student_id varchar(10)
select @student_id=student_id from deleted
if @student_id='admin'
begin
raiserror('错误',16,8)
rollback tran
end
分享到:
- 上一篇:2013 数据结构课程设计(烟