SQL Server触发器和事务用法示例
程序员文章站
2022-03-25 09:49:19
本文实例讲述了sql server触发器和事务用法。分享给大家供大家参考,具体如下:
新增和删除触发器
alter trigger tri_tc on t_c...
本文实例讲述了sql server触发器和事务用法。分享给大家供大家参考,具体如下:
新增和删除触发器
alter trigger tri_tc on t_c for insert,delete as begin set xact_abort on declare @insertcount int; declare @deletecount int; declare @updatecount int; set @insertcount = (select count(*) from inserted); set @deletecount = (select count(*) from deleted); set @updatecount = () if(@insertcount > 0) begin insert into t_c2 select * from inserted; end else if(@deletecount > 0) begin delete t_c2 where exists(select temp.cid from deleted temp where temp.cid=t_c2.cid); end end
更新触发器和事务
事务主要用在数据的保护,在多表更新时,事务保存所有事务下的更新语句就不会提交,数据也就不能更新成功
alter trigger tri_tc_update on t_c for update as begin declare @delcount int; set @delcount = (select count(*) from deleted); if(@delcount > 0) begin begin transaction triupdate --定义事务 declare @cname varchar(100); select @cname = cname from inserted; --保存更新后的内容 update t_c2 set cname = @cname where cid = (select cid from deleted); --更新 if (@@error <> 0) begin rollback transaction triupdate; --事务回滚 end else begin commit transaction triupdate; --事务提交 end end end
存储过程
if(exists(select name from sysobjects s where s.name='pro_fun' and s.type='p')) drop procedure pro_fun go create procedure pro_fun as select * from table go exec pro_fun
游标
declare @qybh varchar(10) declare cur cursor for select distinct qybh from pj_enterpriseinput open cur fetch next from cur into @qybh while @@fetch_status = 0 begin print(@qybh) fetch next from cur into @qybh end close cur deallocate cur
视图
alter view createview as select qybh from createview go
定义方法
alter function funname(@str1 varchar(10),@str2 varchar(10)) returns varchar(10) as begin declare @returnstr varchar(10) set @returnstr = 'false' if(@str1 > @str2) set @returnstr = 'true' return @returnstr end select dbo.funname(... , ...)
定义表变量
declare @qybhtable table (id varchar(32),qybh varchar(30)) insert into @qybhtable select id,qybh from pj_enterpriseinput select * from @qybhtable
case when then 条件统计时的使用
select sum(case when z.watchname='注册监理工程师' then 1 else 0 end), sum(case when z.watchname='xinza' then 1 else 0 end), sum(case when z.watchname='监理员' then 1 else 0 end) from zu_corjl z right join zu_corjltemp t on t.corid=z.corid
希望本文所述对大家sql server数据库程序设计有所帮助。
下一篇: 高并发系统数据幂等的解决方案
推荐阅读
-
SQL server 数据库的索引和视图、存储过程和触发器
-
SQL Server中事务和并发详解
-
SQL Server中的集合运算: UNION, EXCEPT和INTERSECT示例代码详解
-
SQL Server学习笔记之事务、锁定、阻塞、死锁用法详解
-
SQL Server触发器和事务用法示例
-
SQL查询出表、存储过程、触发器的创建时间和最后修改时间示例
-
SQL Server实现split函数分割字符串功能及用法示例
-
SQL Server FOR XML PATH 和 STUFF函数的用法
-
SQL Server 排序函数 ROW_NUMBER和RANK 用法总结
-
SQL Server触发器及触发器中的事务学习