存储过程
create proc StuProc
as //此处 as 不可以省略不写
begin //begin 和 end 是一对,不可以只写其中一个,但可以都不写
select S#,Sname,Sage,Ssex from student
end
go
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 '赵雷' //执行语句
@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
@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
@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
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
as
declare @sname varchar(100)
set @sname=(select Sname from student where S#=01)
select @sname
go
exec StuProc
带输出参数存储过程
if (object_id('proc_getStudentRecord', 'P') is not null)
drop proc proc_getStudentRecord
go
create proc proc_getStudentRecord(
@id int, --默认输入参数
@name varchar(20) out, --输出参数
@age varchar(20) output--输入输出参数
)
as
select @name = name, @age = age from student where id = @id and sex = @age;
go