mssql 触发器问题

xiejiarong 2009-06-08 02:36:53
数据库:database
表名:table

要的结果:1.通过查询分析器加个触发器,要求:在向表table插入数据前执行一条错误的SQL语句来停止插入动作
2.通过查询分析器删除存在的触发器(上面写的触发器)
...全文
49 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
-狙击手- 2009-06-08
  • 打赏
  • 举报
回复
我的是2005讲法,如果是2000参6楼的写法
-狙击手- 2009-06-08
  • 打赏
  • 举报
回复
1、
IF not EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[tr_insert]'))
create trigger tr_insert
......
....




2、

IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[tr_insert]'))
DROP TRIGGER [dbo].[tr_insert]
jimwoo 2009-06-08
  • 打赏
  • 举报
回复
1 if not exists (select 1 from sysobjects where id = object_id(N'tr_insert') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
create trigger tr_insert
2 if exists (select 1 from sysobjects where id = object_id(N'tr_insert') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
drop trigger tr_insert
xiejiarong 2009-06-08
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 happyflystone 的回复:]
create trigger tr_insert
on table
for insert
as
raiserror('insert stop.', 16, 1)
go

--2
DROP TRIGGER tr_insert
[/Quote]


这样可以,
我要再加个需求,
1,添加触发器时加个判断,如果tr_insert不存在就添加,存在则忽略
2,删除触发器时,如果tr_insert 存在就删除,不存在则忽略。
xiejiarong 2009-06-08
  • 打赏
  • 举报
回复
执行 DROP TRIGGER 'tr_insert'
时候
错误提示:
服务器: 消息 170,级别 15,状态 1,行 1
第 1 行: 'tr_insert' 附近有语法错误。
Zoezs 2009-06-08
  • 打赏
  • 举报
回复

create trigger tr_insert
on table
for insert
as
raiserror('insert stop.', 16, 1)
go

--2
DROP TRIGGER 'tr_insert'
ai_li7758521 2009-06-08
  • 打赏
  • 举报
回复
示例:
create table test(ID int,NAME varchar(10),NodeType int,ParentPath varchar(10),Child int,arrChildID varchar(20))
go

create trigger trg_test on test for insert
as
begin
update a
set
Child =a.Child+1,
arrChildID=a.arrChildID+','+rtrim(b.ID)
from
test a,inserted b
where
charindex(',',b.ParentPath)>0
and
cast(a.ID as varchar)=reverse(left(reverse(b.ParentPath),charindex(',',reverse(b.ParentPath))-1))
end
go

insert into test select 1,'新闻中心',1,'0', 0,'1' --Child,arrChildID 让触发器自动维护
insert into test select 2,'图片中心',1,'0', 0,'2'
insert into test select 3,'软件中心',1,'0', 0,'3'
insert into test select 4,'国内新闻',1,'0,1',0,'4'
insert into test select 5,'娱乐新闻',1,'0,1',0,'5'
insert into test select 6,'体育新闻',1,'0,1',0,'6'
insert into test select 7,'热点新闻',1,'0,1',0,'7'
go

select * from test
/*
ID NAME NodeType ParentPath Child arrChildID
----------- ---------- ----------- ---------- ----------- --------------------
1 新闻中心 1 0 4 1,4,5,6,7
2 图片中心 1 0 0 2
3 软件中心 1 0 0 3
4 国内新闻 1 0,1 0 4
5 娱乐新闻 1 0,1 0 5
6 体育新闻 1 0,1 0 6
7 热点新闻 1 0,1 0 7
*/
go

drop trigger trg_test
drop table test
go
-狙击手- 2009-06-08
  • 打赏
  • 举报
回复
create trigger tr_insert
on table
for insert
as
raiserror('insert stop.', 16, 1)
go

--2
DROP TRIGGER 'tr_insert'

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧