SQL 存储过程

分支循环逻辑

begin与end是开始与结束的意思,在这里相当于()。

declare @Id int =1;
if(@Id >1)
begin
   print 'OK'
end
else if(@Id >0)
begin
    set @Id+=10;
   print '0'+@Id
end

视图

优点:

1.方便,把一些常用并且复杂的代码封装成视图,也是使用的时候直接调用不用那么麻烦。

2.安全,这些代码是自己写的,调用者无法看到数据库有关信息。

create view EXView
as
(
  select * from Login//Login为一个表明
)
select * from EXView

事务

事务是指一个工作单元,它包含了一组数据操作命令,并且所有的命令作为一个整体一起向系统提交或撤消请求操作,即这组命令要么都执行,要么都不执行。

这个就是回滚

create table UserTable
(
  UserName nvarchar(50) not null,
  Money decimal not null check(Money>0) 
)
insert into UserTable values ('张三',8000);
insert into UserTable values ('李四',2000);
 select * from UserTable;

begin try
  begin transaction
  update UserTable set Money+=2000 where UserName='张三';
  update UserTable set Money-=2000 where UserName='李四';
  commit transaction
end try
begin catch
 rollback transaction 
end catch 

存储过程

存储过程是一组予编译的SQL语句

它的优点:

1.允许模块化程序设计,就是说只需要创建一次过程,以后在程序中就可以调用该过程任意次。          

2.允许更快执行,如果某操作需要执行大量SQL语句或重复执行,存储过程比SQL语句执行的要快。              

3.减少网络流量,例如一个需要数百行的SQL代码的操作有一条执行语句完成,不需要在网络中发送数百行代码。    

4.更好的安全机制,对于没有权限执行存储过程的用户,也可授权他们执行存储过程。  

缺点:                

1.如果更改范围大到需要对输入存储过程的参数进行更改,或者要更改由其返回的数据,则您仍需要更新程序集中的代码以添加参数、更新 GetValue() 调用,等等,这时候估计比较繁琐了。         

2.可移植性差   

由于存储过程将应用程序绑定到 SQL Server,因此使用存储过程封装业务逻辑将限制应用程序的可移植性。 如果应用程序的可移植性在您的环境中非常重要,则将业务逻辑封装在不特定于 RDBMS 的中间层中可能是一个更佳的选择。

简单的

 proc是 procedure的简写

create  procedure a
as
begin
   print 'OK'
end

exec a

 复杂点的

create procedure Text_Proc
 @Shopper nvarchar(50),
 @Store nvarchar(50),
 @Money int,
 @Bool bit output
 as
 begin
    begin try
	   begin transaction
	   update UserTable set money-=@Money where UserName=@Shopper;
	   update UserTable set Money+=@Money where UserName= @Store;	   
	   commit transaction
	   set @Bool=1;
	end try
	begin catch
	   rollback transaction
	   set @Bool=1;
	end catch
 end

 declare @Bool2 bit
exec Text_Proc  '张三','李四',1000,@Bool2 output
print @Bool2

  

原文地址:https://www.cnblogs.com/mvpbest/p/13221507.html