create table Student(--S# int identity(1,1),S# nvarchar(2),Sname varchar(10),Sage Datetime,Ssex char(2))insert into Student values('01','赵雷','1990-01-01','男');insert into Student values('02','钱电','1990-12-21','男');insert into Student values('03','孙风','1990-05-20','男');insert into Student values('04','李云','1990-08-06','男');insert into Student values('05','周梅','1991-12-01','女');insert into Student values('06','吴兰','1992-03-01','女');insert into Student values('07','郑竹','1989-07-01','女');insert into Student values('08','王菊','1990-01-20','女');drop table Student;select * from Student;
create proc StuProcas //此处 as 不可以省略不写begin //begin 和 end 是一对,不可以只写其中一个,但可以都不写select S#,Sname,Sage,Ssex from studentendgo
create proc StuProc@sname varchar(100) as beginselect S#,Sname,Sage,Ssex from student where sname=@snameendgoexec StuProc '赵雷' //执行语句
上面是在外部给变量赋值,也可以在内部直接给变量设置默认值
create proc StuProc@sname varchar(100)='赵雷'as beginselect S#,Sname,Sage,Ssex from student where sname=@snameendgoexec 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 =1elseset @IsRight=0godeclare @IsRight int exec StuProc '赵雷' , @IsRight outputselect @IsRight
以上是全局变量,下面来了解局部变量
局部变量也称为内部变量。局部变量是在函数内作定义说明的。其作用域仅限于函数内部,离开该函数后再使用这种变量是非法的。局部变量的定义:必须先用Declare命令定以后才可以使用,declare{@变量名 数据类型}局部变量的赋值方法:set{@变量名=表达式}或者select{@变量名=表达式}局部变量的显示:select @变量名create proc StuProcas declare @sname varchar(100)set @sname='赵雷'select S#,Sname,Sage,Ssex from student where sname=@snamegoexec StuProc
那如果是要把局部变量的数据显示出来怎么办呢?
create proc StuProcas declare @sname varchar(100)set @sname=(select Sname from student where S#=01)select @snamegoexec StuProc