事务
事务:保证多个操作全部成功,否则全部失败,这处机制就是事务 思考:下了个订单,但是在保存详细信息时出错了,这样可以成功吗? 数据库中的事务:代码全都成功则提交,如果有某一条语句失败则回滚,整体失败 事务操作: begin transaction--开始事务 comit transaction--提交,没错后执行 rollback transaction--回滚,出错后执行,执行了的操作会回滚,不会生效 用法:声明一个变量,记录错误信息,最终根据变量值是否大于0,进行提交或回滚
示例:模拟转账操作:一个账户扣钱,一个账户加钱
begin transaction declare @sumError int=0 update bank set balance=balance-1000 where cid='0001' set @sumError=@sumError+@@Error update bank set balance=balance+1000 where cid='0002' set @sumError=@sumError+@@Error if(@sumError) begin ? ? ?---失败了 ? ? ?rollback transaction end else begin ? ? ?---成功了 ? ? ?comit transaction end
存储过程
就是一个函数,用于存储一段处理代码 好处: 完成代码的封装,实现代码重用; 安全 方便应用程序与数据库间通信,不用传大量sql语句过程,而只用传一个存储过程名称过来,简单方便 系统存储过程(在界面中打开看一看) 自定义存储过程 create proc usp_test1 参数列表 as 自定义代码段 调用执行:exec 存储过程名称
create proc usp_TwoNumberAdd? @num1 int, @num2 int as? begin ? ?select @num1+@num2 end ----存储过程传参数 ?有几种方式 ----第一种方式 declare @n1 int=45,@n2 int=43 exec usp_TwoNumberAdd @num1=@n1,@num2=@n2 ----第二种方式 exec usp_TwoNumberAdd 21,20
---模糊查询 存储过程 用户传入 宇,和年龄>20返回来有多少条数据,并把这些数据显示出来
create proc usp_SlectStuByNameAndAge @name nvarchar(10),--名字 @age int,--年龄 @count int output --条数 as? begin ? ? set @count=(select count(*) from Student where StuName like @name+'%' and StuAge>@age) ? ? select * from Student where StuName like @name+'%' and StuAge>@age end declare @ct int exec usp_SlectStuByNameAndAge '宇',15,@ct output select @ct

分页的存储过程
---第几页 ---每页多少条 ---总页数返回来 create proc usp_pageUser @page int,--页数 @count int,--条数 @sumPage int output--总页数 as? begin ? ? ?set @sumPage=(CEILING((select count(*) from TblUsers)*1.0/@count))--总页数 ? ? ?select * from? ? ? ? ?(select 编号=ROW_NUMBER()over(order by AutoId),* from TblUsers)as tu ? ? ? ?where tu.编号 between (@page-1)*@count+1 and @page*@count end
---第4页,每页6条 declare @i int exec usp_pageUser 4,6,@i output select @i
触发器
作用:对表进行增、删、改操作时,自动进行一个操作
根据触发机制不同,分为:after触发器,instead of替换触发器
创建触发器:
create trigger 名称?
On 表名
[After|instead of] [insert|delete|update]
As
Begin
…
end
两个临时表:inserted、deleted
示例:删除分公司时,将该分公司的所有部门都删除
建议:对于性能影响太大,所以要慎重使用

(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|