存储过程经典实例

1.任意输入三个数,输出最大的数

 create proc Pr_Test
  @x1 int,
  @x2 int,
  @x3 int
as
  begin
    declare @max int
    if(@x1>@x2)
      set @max=@x1
    else
      set @max=@x2
    if(@x3>@max)
      set @max=@x3

   print '三个数中最大的数是:'+cast(@max as varchar(50))
 end

在正确输入后,执行后就创建了这个存储过程,

下面来执行这个存储过程,任意输入三个数字,具体代码如下:

execute Pr_Test 50,31,48

执行存储过程

结果如下:

三个数中最大的数是:50

2.阶乘之和(如:5!+4!+3!+2!+1!)

create proc Pr_jc
  @x int
as
  begin
   declare @i int,@cj int,@sum int
   select @i=1,@cj=1,@sum=0             
   while @i<=@x                                  
     begin   
      set @cj=@cj*@i                            
      set @sum=@sum+@cj                  
      set @i=@i+1                                 
     end
   print cast(@x as varchar(50))+'阶乘之和是:'+cast(@sum as varchar(50))
  end

执行该存储过程

exec Pr_jc 5

结果如下:

5阶乘之和是:153

3.登录系统存储过程

create proc Pr_denglu
  @hyuser varchar(50),
  @hypwd varchar(50)
as
begin
declare @msg varchar(50)
if(@hyuser='hystu1')
   begin
     if @hypwd='111'
        set @msg='用户名与密码正确,登录成功!'
     else
        set @msg='密码不正确,请重新输入'
   end
else if(@hyuser='hystu2')
   begin
     if @hypwd='222'
        set @msg='用户名与密码正确,登录成功!'
     else
        set @msg='密码不正确,请重新输入'
   end
else if(@hyuser='hystu3')
   begin
     if @hypwd='333'
        set @msg='用户名与密码正确,登录成功'
     else
        set @msg='密码不正确,请重新输入'
   end
else
   set @msg='用户名不正确,请重新输入'
print @msg

end

执行该存储过程

exec Pr_denglu 'hystu1','111'

结果如下:

用户名与密码正确,成功登录!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章