关于sql2005触发器的问题
本帖最后由 fstao 于 2012-12-27 10:49:15 编辑
我有一个表:table1(id int,name varchar(100),sign int),表数据如下:
id name sign
1 a 0
2 b 0
3 c 1
4 d 0
我想在触发器里写一段代码,如果要删除表table1的某一行数据时,如果当前sign=1时,则不能删除,如何写触发器的代码?
------解决方案--------------------CREATE TRIGGER TR_TABLE1_DELETE
ON TABLE1
FOR DELETE
AS
SET NOCOUNT ON;
IF EXISTS ( SELECT 1 FROM DELETED WHERE sign=1
BEGIN
RAISERROR ('提示信息',16,1); -- 如果不需要提示取掉这一句
ROLLBACK TRANSACTION
END
GO
------解决方案----------------------> 测试数据:tb
IF OBJECT_ID('tb') IS NOT NULL DROP TABLE tb
GO
CREATE TABLE tb([id] INT,[name] VARCHAR(1),[sign] INT)
INSERT tb
SELECT 1,'a',0 UNION ALL
SELECT 2,'b',0 UNION ALL
SELECT 3,'c',1 UNION ALL
SELECT 4,'d',0
--------------开始查询--------------------------
GO
CREATE TRIGGER tt ON tb
INSTEAD OF DELETE
AS
BEGIN
DELETE t
FROM tb t ,
DELETED d
WHERE T.[id] = d.[id]
AND d.[sign] <> 1
END
GO
--一次删除一条
DELETE FROM tb WHERE id=3
GO
--批量删除
DELETE FROM tb WHERE id<5
GO
SELECT * FROM tb