--insert trigger
create trigger tri_insert
on student --The name of the table to be changed
for insert --Triggered when inserting a piece of data into the table
as
declare @student_id char(10) --Define a variable
SELECT @student_id=s.student_id from —Assign the value of the specified field queried to the variable
student s inner join inserted i
on s.student_id=i.student_id
if @student_id='0000000001'
begin
raiserror( 'The student number of 1 cannot be inserted!',16,8)
rollback tran
end
go
--update trigger
create trigger tri_update
on student--the name of the table to be changed
for update--to the table Triggered when a piece of data is modified
as
if update(student_id)
begin
Raiserror('Student ID cannot be modified!',16,8)
rollback tran
end
go
--delete trigger
create trigger tri_delete
on student --The name of the table to be changed
for delete --Triggered when a piece of data is deleted from the table
as
declare @student_id varchar(10)
select @student_id=student_id from deleted
if @student_id='admin'
begin
Raiserror('error',16,8)
rollback tran
end
Explanation: When deleting data, you can assume that the database will put the data to be deleted into a deleted temporary table. We can Reading an ordinary table is the same, selecting fields from deleted
and inserting is the same, except that the data to be inserted is placed in the inserted table.
The update operation can be considered as performing two operations. First delete the row record, and then insert it. In this way, the update operation actually operates on the deleted table and the inserted table, so there will be no updated table. Sometimes The two tables have a primary and foreign key relationship. If you want to delete the data in the main table, you will also delete the data related to the sub-table. If you use a trigger at this time, it will have no effect, because this trigger is triggered after you delete the table. At this time, it will be terminated directly and it will prompt "There is a primary and foreign key relationship and cannot be deleted, etc.". All such deletion triggers have no effect