.Net_06_创建存储过程的基本语法(Sql 语句)

--判断存储过程是否存在,存在则删除

if exists(select * from sysobjects where [name]='usp_upGrade')

    drop proc usp_upGrade

go

存储过程
  -> 不带任何参数的存储过程
    create proc 存储过程名
    as
    begin
      SQL语句
    end
  -> 一般系统定义的存储过程是sp_或xp_开头,用户自己定义的存储过程一般使用usp_开头

  -> 代参数的存储过程
    create proc 存储过程名
    @变量名 类型名
    as
    begin
      SQL语句
    end
  -> 实现存储过程分页
  -> 带有默认值的存储过程
    create proc 存储过程名
    @变量名 类型名 = 值
    as
    begin
      SQL语句
    end
  -> 在存储过程中还有一类参数,叫out参数
    create proc 存储过程名
    @参数名 类型名 out
    as
    begin
      SQL语句
    必须为output参数赋值
    end
  -> 在执行完存储过程以后,可以得到这个参数的值
  -> 调用的时候
  exec 存储过程名 @参数 output

分页的例子

 1 --定义存储过程
 2 create proc usp_FenYe
 3 @count int = 30,--参数
 4 @page int = 1--参数
 5 as
 6 begin
 7     select * 
 8     from 
 9     (
10         select ROW_NUMBER() over(order by stuId) as num,
11         *
12         from Student
13     ) as tbl
14     where
15         num between @count * (@page - 1) + 1 and @count * @page;
16 end
17 go

嵌套事务的例子

 1 --转账的例子
 2 create proc usp_Zhuan
 3 @from nvarchar(4),
 4 @to nvarchar(4),
 5 @balance money,
 6 @res int output
 7 as
 8 begin
 9     begin transaction
10         declare @myError int;
11         set @myError = 0;
12     begin try
13         update bank set balance=balance - @balance where cid=@from;
14         update bank set balance=balance + @balance where cid=@to;
15         commit;
16         set @res = 1; --表示成功
17     end try
18     begin catch
19         rollback;
20         set @res = 0; --表示失败
21     end catch
22 end;
23 go

 

posted @ 2013-01-28 03:07  陆俊杰_iOS  阅读(379)  评论(0编辑  收藏  举报

版权信息:©Copyright © 2010-2050 陆俊杰的博客