日期:2014-05-18  浏览次数:20471 次

想建立出发器,在插入的数据重复时候回滚

表data

datacontent
想建立出发器,在插入的数据和datacontent重复时候回滚
如何建立?
下面的代码出错,请帮忙调试.
CREATE   trigGer   [data_DDD]
ON   [dbo].[Data]

After   INSERT,UPDATE
AS
IF   UPDATE   (DataContent)
BEGIN
IF   EXISTS   (SELECT   *
FROM   Data   JOIN   Inserted
  ON   inserted.DataContent
=data.DataContent   )
BEGIN   ROLLBACK
RETURN
END
END




------解决方案--------------------
IF EXISTS (SELECT *
FROM Data inner JOIN Inserted
ON inserted.DataContent
=data.DataContent )

------解决方案--------------------
CREATE trigGer [data_DDD]
ON [dbo].[Data]
After INSERT,UPDATE
AS
IF UPDATE (DataContent)
BEGIN
IF EXISTS (SELECT 1 FROM Data as t INNER JOIN Inserted as i
ON i.DataContent = t.DataContent )
BEGIN
raiserror( '名称重复! ',16,1) /*如果需要反馈请加上此行*/
ROLLBACK /*回滚*/
RETURN
END
END
------解决方案--------------------
alter trigGer [data_DDD] ON [dbo].[Data] after insert,UPDATE AS
IF UPDATE (DataContent)
BEGIN
IF (select count(*) FROM Data where DataContent in(select DataContent from inserted))> =2
BEGIN
ROLLBACK
RETURN
END
END --问题出在你是after触发数据已经更新,此时那样查表无意思,肯定满足你的条件
------解决方案--------------------
楼上的朋友说得对,更正一下:
CREATE trigGer [data_DDD]
ON [dbo].[Data]
After INSERT,UPDATE
AS
IF UPDATE (DataContent)
BEGIN
IF (SELECT count(*) FROM Data as t INNER JOIN Inserted as i
ON i.DataContent = t.DataContent ) > 1
BEGIN
raiserror( '名称重复! ',16,1) /*如果需要反馈请加上此行*/
ROLLBACK /*回滚*/
RETURN
END
END

------解决方案--------------------
谢谢,我知道我也有错,没想到你也没睡,没来得及改