SQL Sever 如何创建存储过程

  

1、为什么要使用存储过程 ?

  过滤SQL语句中的非法字符,执行存储过程比SQL语句快。

2、存储过程能做什么   

   利用存储过程插入数据、修改数据、删除数据

3、实例

//所需数据

//在SQL Sever数据库中创建表

create table tb_stu

(  

  stuNo int primary key,

   stuName varchar(10) not null,  

  stuSex varchar(2) null,  

  stuAge int not null

)

insert into tb_stu values(1,'小张','男',18)

insert into tb_stu values(2,'小丽','女',17)

insert into tb_stu values(3,'小明','男',18)

/*利用存储过程插入数据*/

/*@stuNo,@stuName,@stuSex,@stuAge与数据表对应所需的参数*/

create proc proc_InsertInfo

(  

  @stuNo int,

     @stuName varchar(10),

     @stuSex varchar(2),  

   @stuAge int

)

as

if exists(select*from tb_stu where stuNO=@stuNo)  

  return 0

else

begin

   insert into tb_stu(stuNo,stuName,stuSex,stuAge)   

    values(@stuNo,@stuName,@stuSex,@stuAge)  

  return 1

end

go

/*调用存储过程*/

execute proc_InsertInfo @stuNo=6,@stuName='子',@stuSex='男',@stuAge=18

/*利用存储过程更改数据*/

create proc proc_updateInfo

(  

  @stuNo int,

     @stuName varchar(10),  

  @stuSex varchar(2),

     @stuAge int

)

as

if(@stuNo<>'')  

  update tb_stu set stuName=@stuName, stuSex=@stuSex,stuAge=@stuAge where stuNo=@stuNo

go

/*调用*/

execute proc_updateInfo @stuNo=1,@stuName='小李',@stuSex='女',@stuAge=17

/*利用存储过程删除数据*/

create proc proc_deleteInfo

(  

  @stuNo int

)

as

if(@stuNo<>'')  

  delete from tb_stu where stuNo=@stuNO go

/*调用*/

execute proc_deleteInfo @stuNo=6

/*更改存储过程名称*/

exec sp_rename 'proc_deleteInfo','proc_deleteStuInfo'

/*调用*/

execute proc_deleteStuInfo @stuNo=3

/*更改存储过程*/

alter proc proc_updateInfo

(  

  @stuNo int,  

  @stuName varchar(10),

   /*@stuSex varchar(2),*/

   @stuAge int ) as

if(@stuNo<>'')  

  update tb_stu set stuName=@stuName,stuAge=@stuAge where stuNo=@stuNo

go

/*调用*/

execute proc_updateInfo @stuNo=2,@stuName='小高',@stuAge=18

/*如何查看当前数据库未知存储过程名称*/

select  name from  sysobjects where xtype = 'P'

猜你喜欢

转载自www.cnblogs.com/115Z/p/9853750.html
今日推荐