2017-08-06 128 views
0

我将如何把这个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语句一个try/catch存储过程?

+0

为什么?您希望通过在交易中包装单个声明来完成什么?单个语句是原子的 - 要么是成功的,要么添加行,要么失败,表保持不变。你看了[文档](https://docs.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql)吗?并尝试[Erland的讨论](http://www.sommarskog.se/error_handling/Part1.html),在这一点上可能会有点过分。 – SMor

回答

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