数据库存储过程 基础知识

create proc 存储过程名
--输入参数;当调用存储过程时,所需要输入的数据
--输出参数,从存储过程中赋值后带出数据
as
    --存储过程内容
    return 返回值
go
exce 返回值=存储过程名称 参数一,参数二,..,参数N



--存储过程:相当于C#的函数
--定义变量
declare @bianliang varchar(50)--定义
set @bianliang='12'--赋值
select @bianliang--查询
print @bianliang
---------------定义两个变量求和
declare @bianliang1 int,@bianliang2 int
set @bianliang1=1--赋值
set @bianliang2=2--赋值
select @bianliang1+@bianliang2



--创建存储过程:可编程性→存储过程
create proc chaxun
as--ashe...gou中间写存储过程内容
  select *from student
go  
exec chaxun--执行chaxun存储过程




--带返回值的存储过程
create proc returncount
as
    declare @a int
    select @a=COUNT(*)from student--查询结果赋值给了变量@a
    return @a--储存过程返回值
go
declare @jieshou int--定义一个变量接收存储过程返回值
exec @jieshou=returncount--在执行存储过程时,用接收变量去接收返回值
print @jieshou--输出接收结果




--带输入参数的存储过程
create proc JiaFa
@a int,--输入参数我位置在创建的proc与as之间,定义的时候才加declare,输入参数不能加declare
@b int--输入参数,用“逗号”隔开
as
  return @a+@b
go
declare @a int
exec @a=JiaFa 3,5--带参数的存储过程,需要在存储过程名称之后输入参数,空格隔开,参数之间逗号隔开




--输入一个0-100之间的数,判断是一位数还是两位数,返回1或2,不在范围之内返回-1
create proc pandingshuzi
@a int--存储过程的输入参数
as
  if @a>=0 and @a<10
    begin
        return 1
    end
  else if @a>=10 and @a<100
    begin
        return 2
    end  
  else
    begin
        return -1
    end  
go
declare @a int
exec @a=pandingshuzi 68
print @a   



--累加求和存储过程
create proc he    
@sum int 
as
begin
    declare @shu int =0,@i int =0
        while @i<=@sum
    begin
        set @shu=@i+@shu
        set @i=1+@i
    end
    return @shu
end
go
declare @he11 int
exec @he11=he 10
print @he11

 

posted @ 2015-04-27 10:42  Yusarin  阅读(291)  评论(0编辑  收藏  举报