sql server 插入触发器

2025-03-10 04:40:37
推荐回答(2个)
回答1:

--建立测试数据
if object_id('学生表') is not null drop table 学生表
create table 学生表(id int, name varchar(50))
go

--建立触发器
create trigger ins_trigger on 学生表 instead of insert
as
begin

declare @max int

declare @count int

select @count=count(学生表.id), @max=max(学生表.id)

from 学生表, inserted

where 学生表.id = inserted.id

if @count = 0 insert 学生表 select * from inserted
end
go

--插入数据
insert into 学生表(id,name) values('10','111')
insert into 学生表(id,name) values('10','111')

select * from 学生表

--删除测试环境
drop table 学生表

--查看结果
/*
id name
-------------------
10 111
*/

--对速度应该没有影响,你可以拿一些实际数据试下

回答2:

插入时获取inserted,delete 其并联内容,触发前执行