从这篇开始要总结事务了,我们就从一个简单的事务示例开始吧。下面这个示例首先定义了一个事务,然后把关于一个新订单的数据记录到数据库中。示例代码如下:
USE TSQLFundamentals2008;GO-- 事务-- 一个简单的事务BEGIN TRAN;-- 声明一个变量,保存新的OrderIDDECLARE @neWorderid AS INT=0;-- 将一个新订单插入到Sales.Orders表中INSERT INTO Sales.Orders ( custid , empid , orderdate , requireddate , shippeddate , shipperid , freight , shipname , shipaddress , shipcity , shiPRegion , shippostalcode , shipcountry )VALUES ( 85 , -- custid - int 5 , -- empid - int '20090212' , -- orderdate - datetime '20090301' , -- requireddate - datetime '20090216' , -- shippeddate - datetime 3 , -- shipperid - int 32.38 , -- freight - money N'ship to 85-b' , -- shipname - nvarchar(40) N'6789 rue de l' , -- shipaddress - nvarchar(60) N'Abbaye' , -- shipcity - nvarchar(15) N'Reims' , -- shipregion - nvarchar(15) N'10345' , -- shippostalcode - nvarchar(10) N'France' -- shipcountry - nvarchar(15) ); -- 将新的订单ID保存到变量中SET @neworderid= SCOPE_IDENTITY(); --或者@@IDENTITY-- 返回新的订单IDSELECT @neworderid AS neworderid;-- 将新订单的订单明细插入到Sales.OrderDetails表中INSERT INTO Sales.OrderDetails( orderid ,productid ,unitprice ,qty ,discount)VALUES ( @neworderid,11 ,14.00 ,12 ,0.000), (@neworderid,42,9.80,10,0.000), (@neworderid,72,34.80,5,0.000);-- 提交事务COMMIT TRAN;
插入数据后的效果如下图:
新闻热点
疑难解答