代码改变世界

SQL Proc(存储过程)/tran(事物)

  Evan.Pei  阅读(793)  评论(0编辑  收藏  举报

存储过程好比C#方法

1.事物写在过程里面,直接调用存储过程

1.1没有参数的过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*transaction事物,procedure存储过程*/
create proc CopyTable_1_10000
as
begin tran--开始事物
declare @tran_error int;--声明参数
set @tran_error=0;--给参数赋值
declare @i int,@y int;
set @i=10000;set @y=1;
/*新表不存在时,将数据复制到新表
select * into table_3 from(select*from table_1)as a
*/
while @y<@i   --循环
begin
   /*新表存在,将数据复制*/
   insert into table_3(materialName,Mtype) select materialName,Mtype from table_1
   set @y=@y+1;--循环条件
   set @tran_error=@tran_error+@@ERROR;--事物用于记录错误的系统参数
end
/*判断事物执行是否出错*/
if(@tran_error>0)--@tran_error大于1代表出错,事物回滚
begin
 rollback tran;
 print '事物回滚'
end
else
begin
 commit tran
 print '提交事物'
end<br>--调用存储过程
exec CopyTable_1_10000

1.2带传参的过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
--PROC带参数
create proc showDescription
@Mtype int--需要传递的参数
as
begin
select * into  #table_3 from
(select table_1.materialName,table_2.MtypeDescription from table_1 left join table_2
 on table_1.Mtype=table_2.id
 where table_1.Mtype=@Mtype)as c
 select * from #table_3
end
--调用,传递@Mtype参数
exec showDescription @Mtype=2
--删除
drop proc showDescription

  1.3带输出参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if exists (select * from sys.procedures where name ='proc_getCourseInfo')
drop proc proc_getCourseInfo
go
create proc proc_getCourseInfo
@gradeid int,
@outparameter int output--输出参数
as
begin
select g.g_banji,c.c_CourseName,c.c_teacher,c.c_date,c.c_time from Course c left join grade g on c.c_gradeid=g.g_id where g.g_id=@gradeid;
select @outparameter=COUNT(*) from Course;
end
 
declare @p int
exec proc_getCourseInfo @gradeid=2,@outparameter=@p output
select @p

  

 

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示