使用事务的try / catch中的存储过程

时间:2017-08-06 22:40:11

标签: sql-server transactions try-catch

我如何设置此SQL Server语句

USE OnlineStore
GO

CREATE PROC dbo.spInsertNewProduct
AS
BEGIN
    INSERT INTO Product (Name, Size, SalePrice, Category, Department, Location, Description, ProductCondition, SKU, Colors, LastOrderDate, InventoryQuantity, AverageRating)
    VALUES ('King Arthur: Legend of the Sword (Blu-Ray)', 
            '5 3/8” wide x 6 3/4” tall and 1/2” thick', 24.99, 
            'Blu-Ray', 'Movies', 'Ontario', 
            'Blu-Ray of King Arthur: Legend of the Sword', 'New', '324510', 
            'Blue', '2017-8-3', 17, 86)
END

在使用交易的try / catch中?

1 个答案:

答案 0 :(得分:1)

正如SMor在评论中所建议的那样,插入没有任何意义,它要么进入要么不进行,所以实际上没有什么可以回滚的。但是,如果您希望实现try / catch,syntax将是:

USE OnlineStore
GO

CREATE PROC dbo.spInsertNewProduct
AS
BEGIN
        BEGIN TRY
            BEGIN TRAN
            INSERT INTO Product (Name, Size, SalePrice, Category, Department, Location, [Description], ProductCondition, SKU, Colors, LastOrderDate, InventoryQuantity, AverageRating)
            VALUES ('King Arthur: Legend of the Sword (Blu-Ray)', 
                    '5 3/8” wide x 6 3/4” tall and 1/2” thick', 24.99, 
                    'Blu-Ray', 'Movies', 'Ontario', 
                    'Blu-Ray of King Arthur: Legend of the Sword', 'New', '324510', 
                    'Blue', '2017-8-3', 17, 86)
            COMMIT TRAN
        END TRY
        BEGIN CATCH
            ROLLBACK TRAN
        END CATCH
END