您的位置:首页 > 数据库

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

2013-01-28 03:07 666 查看
--判断存储过程是否存在,存在则删除

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

分页的例子

--定义存储过程
create proc usp_FenYe
@count int = 30,--参数
@page int = 1--参数
as
begin
select *
from
(
select ROW_NUMBER() over(order by stuId) as num,
*
from Student
) as tbl
where
num between @count * (@page - 1) + 1 and @count * @page;
end
go


嵌套事务的例子

--转账的例子
create proc usp_Zhuan
@from nvarchar(4),
@to nvarchar(4),
@balance money,
@res int output
as
begin
begin transaction
declare @myError int;
set @myError = 0;
begin try
update bank set balance=balance - @balance where cid=@from;
update bank set balance=balance + @balance where cid=@to;
commit;
set @res = 1; --表示成功
end try
begin catch
rollback;
set @res = 0; --表示失败
end catch
end;
go
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: