当前位置: 代码迷 >> Sql Server >> sql 触发器 触发的内容是提醒性文字改如何写
  详细解决方案

sql 触发器 触发的内容是提醒性文字改如何写

热度:39   发布时间:2016-04-24 09:21:59.0
sql 触发器 触发的内容是提醒性文字改怎么写?
如题 : 例如 tb 表里面 id 字段和code字段,如更新表里面的某一个字段的时候 判断如果code为空 就提示错误信息,
“code为空不能进行跟新”
oracle我知道怎么写 SQLSERVER不知道该怎么写才可以。
------解决思路----------------------
CREATE TABLE TB20150202001(
ID INT
)
GO
CREATE TRIGGER TRG_TRG_20150202001
ON TB20150202001
INSTEAD OF INSERT
AS
BEGIN
IF 1=1
RAISERROR(N'自定义错误.',10,1)
    ELSE
SELECT 1
END
GO
INSERT INTO TB20150202001
SELECT 1

SELECT * FROM TB20150105001
类似这样
------解决思路----------------------

create table tb(id int,code varchar(10))

insert into tb
 select 1,'aaa' union all
 select 2,'bbb'


-- 建触发器
create trigger tr_tb on tb
for update
as
begin
 if exists(select 1 
           from inserted
           where code is null or code='')
 begin
  raiserror('code为空不能进行更新',18,18)
  rollback tran
 end
end


-- 测试1
update tb set code='ccc' where id=1
/*
(1 row(s) affected)
*/


-- 测试2
update tb set code='' where id=2
/*
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
Msg 50000, Level 18, State 18, Procedure tr_tb, Line 10
code为空不能进行更新
*/


-- 测试3
update tb set code=null
/*
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
Msg 50000, Level 18, State 18, Procedure tr_tb, Line 10
code为空不能进行更新
*/


-- 结果
select * from tb
/*
id          code
----------- ----------
1           ccc
2           bbb

(2 row(s) affected)
*/
  相关解决方案