标签:upd script ESS class const alt ber compute begin
事务就是作为一个逻辑工作单元的SQL语句,如果任何一个语句操作失败那么整个操作就被失败,以后操作就会回滚到操作前状态,或者是上个节点。为了确保要么执行,要么不执行,就可以使用事务。而锁是实现事务的关键,锁可以保证事务的完整性和并发性。
代码实例
USE [MyDataBase] GO /****** Object: Table [dbo].[Money] Script Date: 2019/2/2 17:07:03 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Money]( [ID] [bigint] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NOT NULL, [Money] [decimal](18, 0) NOT NULL, CONSTRAINT [PK_tb_Money] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET IDENTITY_INSERT [dbo].[Money] ON INSERT [dbo].[Money] ([ID], [Name], [Money]) VALUES (1, N‘张三‘, CAST(1000 AS Decimal(18, 0))) INSERT [dbo].[Money] ([ID], [Name], [Money]) VALUES (2, N‘李四‘, CAST(1000 AS Decimal(18, 0))) SET IDENTITY_INSERT [dbo].[Money] OFF
BEGIN TRAN Tran_Money; --开始事务 DECLARE @tran_error INT; SET @tran_error = 0; BEGIN TRY UPDATE dbo.Money SET Money = Money - 30 WHERE Name = ‘张三‘; SET @tran_error = @tran_error + @@ERROR; --测试出错代码,看看张三的钱减少,李四的钱是否会增加 --SET @tran_error = 1; UPDATE dbo.Money SET Money = Money + 30 WHERE Name = ‘李四‘; SET @tran_error = @tran_error + @@ERROR; END TRY BEGIN CATCH PRINT ‘出现异常,错误编号:‘ + CONVERT(VARCHAR, ERROR_NUMBER()) + ‘,错误消息:‘ + ERROR_MESSAGE(); SET @tran_error = @tran_error + 1; END CATCH; IF ( @tran_error > 0 ) BEGIN --执行出错,回滚事务 ROLLBACK TRAN; PRINT ‘转账失败,取消交易!‘; END; ELSE BEGIN --没有异常,提交事务 COMMIT TRAN; PRINT ‘转账成功!‘; END
数据库中的锁也是为了解决在并发访问时出现各种冲突的一种机制
主要解决多个用户同时对数据库的并发操作时会带来以下数据不一致的问题:
并发控制的主要方法是封锁,锁就是在一段时间内禁止用户做某些操作以避免产生数据不一致
标签:upd script ESS class const alt ber compute begin
原文地址:https://www.cnblogs.com/cnki/p/8715522.html