在TRANSACTION中尝试捕获

时间:2017-05-24 08:24:43

标签: sql-server

我编写了一个过程,从表中选择列并插入到另一个表中。

我在事务中放了一个try / catch块。如果我之间有任何错误,那么我的代码会将错误详细信息插入错误日志表并回滚事务。

IF OBJECT_ID('usp_Stage_raw_ADDM_ALL') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[usp_Stage_raw_ADDM_ALL]
    PRINT 'Procedure usp_Stage_raw_ADDM_ALL Dropped'
END
GO

CREATE PROC [dbo].[usp_Stage_raw_ADDM_ALL] AS

SET ANSI_NULLS ON
GO
SET NOCOUNT ON
GO
SET XACT_ABORT ON
GO
SET QUOTED_IDENTIFIER ON
GO

BEGIN TRANSACTION; 

BEGIN TRY
DELETE FROM tbl_Staging_Devices WHERE [Source] LIKE 'ADDM%'
INSERT INTO tbl_Staging_Devices 
(
    Device_Name,
    Serial_Number,
    Company,

)
SELECT [Computer Name] AS Device_Name,
Serial_Number = 
    CASE
        WHEN [Serial Number]='None' THEN NULL
        ELSE [Serial Number]
    END,
Company = 'Car'
FROM (
    Select * From raw_ADDM_PCL
    UNION ALL
    Select * From raw_ADDM_CCL) a

END TRY

   BEGIN CATCH
      IF @@TRANCOUNT > 0  
        EXEC USP_InsertErrorDetails
        ROLLBACK TRANSACTION; 
    END CATCH

   IF @@TRANCOUNT > 0  
    COMMIT TRANSACTION;

    IF OBJECT_ID('usp_Stage_raw_ADDM_ALL') IS NOT NULL
BEGIN
    PRINT 'Procedure usp_Stage_raw_ADDM_ALL Created'
END
GO

2 个答案:

答案 0 :(得分:4)

你创建的sp所做的就是

SET ANSI_NULLS ON

您的代码使用GO分批分割,而您的SP代码只有一个:

CREATE PROC [dbo].[usp_Stage_raw_ADDM_ALL] AS
SET ANSI_NULLS ON
GO

你无法插入"去"在您的程序中,"去"表示批处理已完成,代码已提交给服务器,现在您只提交一条语句提交CREATE PROC代码

答案 1 :(得分:1)

这是解决方案。

CREATE PROC [dbo].[usp_Stage_raw_ADDM_ALL] 
AS
BEGIN

SET ANSI_NULLS ON
SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON

BEGIN TRY
BEGIN TRANSACTION
DELETE FROM tbl_Staging_Devices WHERE [Device_Name] LIKE 'ADDM%'

INSERT INTO tbl_Staging_Devices 
(
Device_Name,
Serial_Number,
Company
)
SELECT [Computer Name] AS Device_Name,
Serial_Number = 
CASE
WHEN [Serial Number]='None' THEN NULL
ELSE [Serial Number]
END,
Company = 'Car'
FROM (
Select * From raw_ADDM_PCL
UNION ALL
Select * From raw_ADDM_CCL) a
COMMIT TRANSACTION;
END TRY

   BEGIN CATCH
      IF @@TRANCOUNT > 0  
        EXEC USP_InsertErrorDetails
   ROLLBACK TRANSACTION; 
END CATCH
END