从SQL代理作业调用时,工作存储过程失败

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从SQL代理作业调用时,工作存储过程失败相关的知识,希望对你有一定的参考价值。

我有一个运行良好的存储过程,SQL Server Management Studio中没有错误。但是,当作为SQL代理作业的一个步骤执行相同的存储过程时,它将终止于:

错误3930:无法提交当前事务,并且无法支持写入日志文件的操作。回滚交易。

存储过程位于名为[Billing]的模式中。它使用的大多数表也在[Billing]模式中。

主存储过程开始数据库事务。主存储过程调用的存储过程在该继承的事务上完成所有工作。主存储过程负责提交或回滚事务。

运行SQL代理作业步骤的数据库用户不是Sysadmin角色,也不是dbo。它属于db_datareader和db_datawriter数据库角色,并且已在[Billing]架构中获得删除,执行,插入,引用,选择和更新权限。

这是主存储过程:

CREATE PROCEDURE [Billing].[GenerateBillXml]
  @pUseProductionPsSystem bit
  ,@pPeriodYear int
  ,@pPeriodMonthNumber int
  ,@pDocumentTypeName varchar(20)
  ,@pUser varchar(100)
  ,@pFilePath varchar(500)
  ,@pExportDateTime datetime2(7)
  ,@pResultCode int = 0 OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

  SET @pResultCode = 0;

  DECLARE @transactionBegun bit = 0
          ,@RC int = 0
          ,@processDateTimeUtc datetime2(7) = GETUTCDATE()
          ,@billGenerationId int
          ,@PsJobSuffix char(2)
          ,@periodDate date
          ,@periodDateString char(6)
          ,@PsBaseJobNumber char(6)
          ,@okayToRun int = 0
          ,@msg varchar(500);

  BEGIN TRY
    /* calculate the period date */
    SET @periodDate = CONVERT(date,CAST(@pPeriodMonthNumber as varchar) + '/01/' + CAST(@pPeriodYear as varchar))
    SET @periodDateString = CONVERT(varchar, @periodDate, 12); -- yyMMdd

    /* retrieve the job suffix */
    SELECT @PsJobSuffix = CAST([PsJobSuffix] as char(2))
      FROM [dbo].[DocumentType] dt
      WHERE [Name] like @pDocumentTypeName;

    /* build the base job number */
    SET @PsBaseJobNumber = LEFT(@periodDateString, 4) + @PsJobSuffix

    /*
     * We've made it past the input check - record the fact that we're generating a bill
     */
    INSERT [Billing].[BillGeneration] (
      [PsBaseJobNumber], [Status], [RunBy], [ProcessDateTimeUtc]
    ) VALUES (
      @PsBaseJobNumber, 'Running', @pUser, @processDateTimeUtc
    );

    IF @@ROWCOUNT = 1
      SET @billGenerationId = SCOPE_IDENTITY();

    EXECUTE @RC = [Billing].[_0_OkayToGenerateBill]
      @PsBaseJobNumber
      ,@okayToRun OUTPUT
      ,@pResultCode OUTPUT;

    IF @pResultCode = 0  
    BEGIN
      -- called stored procedure completed without error
      IF @okayToRun = -1 -- this bill has already been generated
      BEGIN
        SET @msg = 'The billing for job ' + CAST(@PsBaseJobNumber as varchar) + ' has already been produced.';
        RAISERROR(@msg, 16, 1)
      END

      IF @okayToRun = -2 -- too early to run billing for this period
      BEGIN
        SET @msg = 'It is too early to generate billing for job ' + CAST(@PsBaseJobNumber as varchar) + '.';
        RAISERROR(@msg, 16, 1)
      END

      IF @okayToRun <> 1 -- unknown error...
      BEGIN
        SET @msg = 'Unknown error occured while determining whether okay to generate bill for job ' + CAST(@PsBaseJobNumber as varchar) + '.';
        RAISERROR(@msg, 16, 1)
      END
    END
    ELSE
    BEGIN
      SET @msg = 'Unknown failure in sub-stored procedure [Billing].[_0_OkayToRun]() for job ' + CAST(@PsBaseJobNumber as varchar) + '.';
      RAISERROR(@msg, 16, 1)  -- will cause branch to CATCH
    END

    /* Okay to generate bill */

    /* If not in a transaction, begin one */
    IF @@TRANCOUNT = 0
    BEGIN
      BEGIN TRANSACTION
      SET @transactionBegun = 1;
    END

    EXECUTE @RC = [Billing].[_1_GeneratePsPreBillData] 
       @PsBaseJobNumber
      ,@pUser
      ,@pResultCode OUTPUT;

    IF @pResultCode = 0
    BEGIN
      -- stored proced ran to successful completion
      EXECUTE @RC = [Billing].[_2_GetBillingDataForXmlGeneration]
         @pUseProductionPsSystem
        ,@PsBaseJobNumber
        ,@pResultCode OUTPUT;

      IF @pResultCode = 0
      BEGIN
        -- stored proced ran to successful completion
        IF @transactionBegun = 1
          -- all table data has been created/updated
          COMMIT TRANSACTION

        -- Output XML bill to file
        EXECUTE @RC = [Billing].[_3_GenerateBillingXmlFilesForPsJob] 
           @PsBaseJobNumber
          ,@pFilePath
          ,@pExportDateTime
          ,@pResultCode OUTPUT;

        IF @pResultCode <> 0
        BEGIN
          -- called stored procedure failed
          SET @msg = '[Billing].[_3_GenerateBillingXmlFilesForPsJob]() failed for job ' + CAST(@PsBaseJobNumber as varchar);
          RAISERROR(@msg, 16, 1)  -- will cause branch to CATCH
        END
      END
      ELSE
      BEGIN
        -- called stored procedure failed
        SET @msg = '[Billing].[_2_GetBillingDataForXmlGeneration]() failed for job ' + CAST(@PsBaseJobNumber as varchar);
        RAISERROR(@msg, 16, 1)  -- will cause branch to CATCH
      END
    END
    ELSE
    BEGIN
        -- called stored procedure failed
      SET @msg = '[Billing].[_1_GeneratePsPreBillData]() failed for job ' + CAST(@PsBaseJobNumber as varchar);
      RAISERROR(@msg, 16, 1)  -- will cause branch to CATCH
    END

    -- bill generation was successful
    IF @billGenerationId IS NOT NULL
      UPDATE [Billing].[BillGeneration]
        SET [Status] = 'Successful', [ProcessEndDateTimeUtc] = GETUTCDATE()
        WHERE [Id] = @billGenerationId;

  END TRY
  BEGIN CATCH
    -- rollback transaction if we started one
    IF @transactionBegun = 1
      ROLLBACK TRANSACTION

    -- record the error
    INSERT [Billing].[BillGenerationError] (
      [DateTime], [Object], [ErrorNumber], [ErrorMessage]
    ) VALUES (
      GETDATE(), OBJECT_NAME(@@PROCID), ERROR_NUMBER(), ERROR_MESSAGE()
    );

    -- bill generation failed
    IF @billGenerationId IS NOT NULL
      UPDATE [Billing].[BillGeneration]
        SET [Status] = 'Failed'
            ,[Note] = ERROR_MESSAGE()
            ,[ProcessEndDateTimeUtc] = GETUTCDATE()
        WHERE [Id] = @billGenerationId;

    SELECT ERROR_NUMBER() as ErrorNumber;
    SELECT ERROR_MESSAGE() as ErrorMessage;
    SET @pResultCode = 1
  END CATCH
END
答案

正如@Lukasz Szozda在他的一条评论中暗示我的问题,问题是当SQL Agent作业执行BCP.EXE命令时,它在SQL Agent使用的服务帐户下运行,对我来说这是相当严格的“本地系统” “帐户。在这一点上,我很明显必须使用代理帐户。所以我在Operating System (CmdExec)下创建了一个代理,这是唯一有意义的选择。

我回到工作步骤将其更改为使用代理,但后来注意到,在其当前类型的Transact-SQL script (TSQL)中,无法分配代理帐户。

在尝试了一些事情后,最终决定将作业步骤中的TSQL语句放入新的存储过程,然后从SQL命令行可执行文件SQLCMD.EXE调用该存储过程。然后我将工作步骤类型从Transact-SQL script (TSQL)更改为Operating System (CmdExec)。然后我可以将Run As字段设置为我之前创建的代理。我指定命令运行为CMD.EXE /c SQLCMD.EXE -S [ServerName] -Q "EXEC [NewProcedureName] [parameters]"

如果你很好奇为什么我在SQLCMD.EXE下运行CMD.EXE,那是因为新存储过程的一个参数是特定格式的当前日期('%date:~4,10%'),SQL Server作业执行环境不支持,但CMD.EXE肯定会。

总的来说,我认为这比我预期的要多一些。

以上是关于从SQL代理作业调用时,工作存储过程失败的主要内容,如果未能解决你的问题,请参考以下文章

sql server 2008,SP_OACreate手动执行成功,代理作业定时执行失败?

从存储过程执行 SQL Server 代理作业并返回作业结果

如何查找调用给定存储过程的所有 SQL 代理作业

SQL 代理作业中的批量插入失败,未找到文件

使用 ssis 包在 SQL Server 代理作业中找不到存储过程错误

调用SQL存储过程的C#函数在从本地计算机使用时有效,但在从云中的Azure函数调用时失败