代码之家  ›  专栏  ›  技术社区  ›  Chris L

TSQL-在事务语句中创建存储过程

  •  7
  • Chris L  · 技术社区  · 16 年前

    关键字“procedure”附近的语法不正确。

    我创建了这个示例脚本来说明

    Begin Try
    Begin Transaction 
        -- do a bunch of add/alter tables here
        -- do a bunch of data manipulation/population here
    
        -- create a stored proc
      create procedure dbo.test
      as
      begin
        select * from some_table
      end
    Commit  
    End Try
    Begin Catch
        Rollback  
        Declare @Msg nvarchar(max)
        Select @Msg=Error_Message();
        RaisError('Error Occured: %s', 20, 101,@Msg) With Log;
    End Catch
    

    4 回复  |  直到 14 年前
        1
  •  13
  •   KM.    16 年前

    试着做 create procedure 在里面 EXEC('...') ,如下所示:

    Begin Try
    Begin Transaction 
        -- do a bunch of add/alter tables here
        -- do a bunch of data manipulation/population here
    
        -- create a stored proc
      EXEC ('create procedure dbo.test
      as
      begin
        select * from some_table
      end')
    Commit  
    End Try
    Begin Catch
        Rollback  
        Declare @Msg nvarchar(max)
        Select @Msg=Error_Message();
        RaisError('Error Occured: %s', 20, 101,@Msg) With Log;
    End Catch
    
    GO
    
        2
  •  12
  •   Thomas    12 年前

    Set Xact_Abort On
    GO
    Begin Transaction 
    GO
    If object_id('tempdb..#tmpErrors') is not null
        Drop Table #tmpErrors
    GO
    Create Table #tmpErrors( [Error] int not null )
    GO
    Create Procedure dbo.Test
    As
    Begin
        --....
    End
    GO
    If @@Error <> 0 AND @@TranCount >0 Rollback Transaction
    GO
    IF @@TranCount = 0 Begin Insert #tmpErrors (Error) Select 1 Begin Transaction End
    GO
    
    -- more statements
    
    GO
    If @@Error <> 0 AND @@TranCount >0 Rollback Transaction
    GO
    IF @@TranCount = 0 Begin Insert #tmpErrors (Error) Select 1 Begin Transaction End
    GO
    
    --.....
    
    IF NOT EXISTS(SELECT * FROM #tmpErrors)
        BEGIN
            PRINT 'The database update succeeded'
            IF @@TRANCOUNT > 0 COMMIT TRANSACTION
        END
    ELSE 
        BEGIN
            PRINT 'The database update failed'
            IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
        END
    GO
    
    DROP TABLE #tmpErrors
    GO
    
        3
  •  2
  •   user1035920 user1035920    15 年前

    KM提出的解决方案存在各种问题:

    • 如果您在EXEC()调用中输入的内容在语义上不正确(例如,您将一个不存在的表从存储过程内部放入),则不会出现错误,也不会回滚事务。

    • 如果您的SELECT bubbles在语法上完全不正确,那么SELECT bubbles的调用在语法上是错误的,但是如果您将SELECT bubbles的调用存储在一个完全错误的SELECT()过程中:

      A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.)
      

        4
  •  0
  •   Richard    16 年前

    推荐文章