您的位置:首页 > 数据库

SQL Server之存储过程基础知识

2015-08-23 21:15 381 查看
From:http://www.cnblogs.com/jiajiayuan/archive/2011/06/15/2081201.html

无参数存储过程:
选出Student表中的所有信息,

create proc StuProc
as //此处 as 不可以省略不写
begin //begin 和 end 是一对,不可以只写其中一个,但可以都不写
select S#,Sname,Sage,Ssex from student
end
go
有参数存储过程:
全局变量
全局变量也称为外部变量,是在函数的外部定义的,它的作用域为从变量定义处开始,到本程序文件的末尾。
选出指定姓名的学生信息:

复制代码
create proc StuProc
@sname varchar(100)
as
begin
select S#,Sname,Sage,Ssex from student where sname=@sname
end
go

exec StuProc '赵雷' //执行语句
复制代码
上面是在外部给变量赋值,也可以在内部直接给变量设置默认值

复制代码
create proc StuProc
@sname varchar(100)='赵雷'
as
begin
select S#,Sname,Sage,Ssex from student where sname=@sname
end
go

exec StuProc
复制代码
也可以把变量的内容输出,使用output

复制代码
create proc StuProc
@sname varchar(100),
@IsRight int output //传出参数
as
if exists (select S#,Sname,Sage,Ssex from student where sname=@sname)
set @IsRight =1
else
set @IsRight=0
go

declare @IsRight int
exec StuProc '赵雷' , @IsRight output
select @IsRight
复制代码
以上是全局变量,下面来了解局部变量
局部变量也称为内部变量。局部变量是在函数内作定义说明的。其作用域仅限于函数内部,离开该函数后再使用这种变量是非法的。
局部变量的定义:必须先用Declare命令定以后才可以使用,declare{@变量名 数据类型}
局部变量的赋值方法:set{@变量名=表达式}或者select{@变量名=表达式}
局部变量的显示:select @变量名

复制代码
create proc StuProc
as
declare @sname varchar(100)
set @sname='赵雷'
select S#,Sname,Sage,Ssex from student where sname=@sname
go

exec StuProc
复制代码
那如果是要把局部变量的数据显示出来怎么办呢?

复制代码
create proc StuProc
as
declare @sname varchar(100)
set @sname=(select Sname from student where S#=01)
select @sname
go

exec StuProc
复制代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: