SQL Server'在' Try / Catch'中执行As' / Revert模式块

时间:2013-05-02 16:13:24

标签: sql-server try-catch revert execute-as

我希望确保在SQL Server 2012上的Try / Catch块中使用Execute As / Revert时使用“最佳”模式。下面的代码“似乎”表现正常...我错过了什么或者是否有任何安全问题,“更好”的方法等?

以下是我的代码:

CREATE PROCEDURE [dbo].[TryItOut]
WITH EXECUTE as 'NoTable1Access' --does not have access (select) to Table1!
AS
Begin
  Declare @execErrorNumber int,
           @execErrorMessage nvarchar(2048),
           @xactState smallint

  Begin Try
    Execute as user='HasTable1Access'
    select *, 1/0 as [SimulateError] from [T1].[Table1]; -- This will be a Stored Procedure call, but a select statement was easier to demo...
    Revert --Revert on 'HasTable1Access'
  End Try
  Begin Catch;

        select @execErrorNumber = ERROR_NUMBER(),
               @execErrorMessage = ERROR_MESSAGE(),
               @xactState = XACT_STATE();

        Revert -- Revert on 'HasTable1Access' when in error...
        --Do some error processing in context of 'NoTable1Access'
   End Catch 

   select * from [T1].[Table1] --Should NOT have any access now and select should fail...
End

0 个答案:

没有答案