存储过程

----------------存储过程
--------存储过程相当于C#里的方法
-------存储过程:存储在数据库里面的,处理数据的过程(sql语句)
create proc GetStu  --创建存储过程
as     --关键字
begin   --如果只有一条语句,可以省略begin end
select * from Students
end


ALTER proc GetStu  --修改存储过程
as     --关键字
begin   --如果只有一条语句,可以省略begin end
select * from Students
end

exec Getstu --执行存储过程

exec sp_databases --获取数据库所有的数据库
exec sp_tables null,'dbo'
exec sp_columns 'Bank' --打出表里面的字段


--带参数的存储过程
create proc Getstu1
@id int =1    --定义存储过程的参数,不需要使用declare并且应该放在as前面,可以给定义的参数赋初始值
as
begin
select *from Students where Id=@id
end
exec Getstu1 2 --调用一个带参数的存储过程,参数在存储过程名字后面加上一个空格

----存储过程
create proc Getstu2
@id int =1 ,
@name nvarchar(10)   --定义多个参数需要用逗号隔开
as
begin
select *from Students where Id=@id and Name =@name
end
exec Getstu2 2,'bbbb'--传两个参数需要用逗号隔开
exec getstu2 @id=2, @name='bbbb'
exec getstu2  @name='bbbb'  --有默认值的可以不传参数,没有默认值的必须传参

-------带输出参数的存储过程
create proc Getstu3
@id int =1 ,
@name nvarchar(10),   --定义多个参数需要用逗号隔开
@totalCount int =0 output --输出参数可以带默认值
as
begin
select *from Students where Id=@id
select @totalCount=COUNT(Id) from Students
end

declare @total int
exec Getstu3 2,'bbbb',@totalCount=@total output--传多个参数需要用逗号隔开,如果是输出参数应该放在最后面并且要跟上output关键字
select @total

原文地址:https://www.cnblogs.com/sumg/p/3649476.html