当前位置:  开发笔记 > 编程语言 > 正文

如何取消SQL中的删除

如何解决《如何取消SQL中的删除》经验,为你挑选了2个好方法。

我想创建一个触发器来检查针对业务规则删除的内容,然后在需要时取消删除.有任何想法吗?

该解决方案使用了"替代删除"触发器.Rollback tran停止了删除.当我做删除时,我担心会遇到级联问题,但似乎没有发生.也许触发器无法触发自身.



1> Tomalak..:

使用INSTEAD OF DELETE(参见MSDN)触发器并在触发器内决定您真正想要做什么.



2> Leo Moore..:

该解决方案使用了"替代删除"触发器.Rollback tran停止了删除.当我进行删除时,我担心会遇到级联问题,但这似乎不会发生.也许触发器无法触发自身.无论如何,谢谢大家的帮助.

ALTER TRIGGER [dbo].[tr_ValidateDeleteForAssignedCalls]
on [dbo].[CAL]
   INSTEAD OF DELETE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @RecType VARCHAR(1)
    DECLARE @UserID VARCHAR(8)
    DECLARE @CreateBy VARCHAR(8)
    DECLARE @RecID VARCHAR(20)

    SELECT @RecType =(SELECT RecType FROM DELETED)
    SELECT @UserID =(SELECT UserID FROM DELETED)
    SELECT @CreateBy =(SELECT CreateBy FROM DELETED)
    SELECT @RecID =(SELECT RecID FROM DELETED)

     -- Check to see if the type is a Call and the item was created by a different user
    IF @RECTYPE = 'C' and not (@USERID=@CREATEBY)

    BEGIN
        RAISERROR ('Cannot delete call.', 16, 1)
        ROLLBACK TRAN
        RETURN
    END

     -- Go ahead and do the update or some other business rules here
    ELSE
        Delete from CAL where RecID = @RecID    

END

推荐阅读
sx-March23
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有