sql存储过程

1.在数据库中保存的存储过程都是编译过的,执行速度快。

2.允许模块化编程,类型方法的复用。

3.提高了性能的安全性,防止sql注入。

4.调用时减少网络流通量,只传输存储过程名称。

系统存储过程一般以sp_或xp_开头,用户存储过程一般以usp_开头。

调用存储过程用关键字exec

1.创建一个名为usp_helloworld存储过程

create proc usp_helloworld
as
begin
    print 'hello world!!!';
end
exec usp_helloworld

2.创建一个带参数存储过程,并输出两个的和。

--带参数存储过程
create proc usp_add
    @i1 int,
    @i2 int
as
begin
    print @i1+@i2
end

调用的时候要传递两个参数

exec usp_add 100,200

3.如果已经存在的存储过程名称,要通过alter修改。

设置变量@i2的默认值,有默认值的参数可以传递参数值。

alter proc usp_add
    @i1 int,
    @i2 int =100
as
begin
    print @i1+@i2
end
exec usp_add 500
--输出结果为600

4.如果第一个无默认,第二个有默认值,只给第一个传值,可以采用显示传值。

exec usp_add @i1=500
exec usp_add @i2=100,@i1=300

5.有返回值的存储过程

声明output类型变量,类型C#中的out。

alter proc usp_add
    @i1 int,
    @i2 int =100,
    @sum int output
as
begin
    print @i1+@i2
end

declare @val int
exec usp_add @i1=2000,@i2=500,@sum=@val output
print @val

6.让英语及格成绩超过一半。

如果成绩不足一半,循环执行加分操作,直到及格成绩达到半数。

create proc usp_promote
@passline int=60
as 
begin
    declare @count int,@loser int,@halfCount int
    set @count=(select count(*) from scores)
    set @loser=(select count(*) from scores where english<@passline)
    set @halfCount = ceiling(@count/2.0)
    while @halfCount<@loser
    begin 
        update scores set english=english+2 where english<@passline
        set @loser=(select count(*) from scores where english<@passline)
    end
end

exec usp_promote

 

 

posted @ 2013-01-14 15:35  life is a gift  阅读(243)  评论(0编辑  收藏  举报