存储过程(Stored Procedure)是在大型数据库系统中,一组为了完成特定功能的SQL语句集
它存储在数据库中,一次编译后永久有效,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它
存储过程是数据库中的一个重要对象
优点
1.执行速度更快 – 在数据库中保存的存储过程语句都是编译过的
2.允许模块化程序设计 – 类似方法的复用
3.提高系统安全性 – 防止SQL注入
4.减少网络流通量 – 只要传输存储过程的名称
系统存储过程一般以sp开头,用户自定义的存储过程一般以usp开头
语法
create proc 存储过程名@参数1 数据类型 [=默认值] [output], -- "[" 里面的内容表示可选项@参数2 数据类型 [=默认值] [output],...asSQL语句
案例:根据姓名和年龄查询学生信息
-- 1 定义存储过程:create proc usp_StudentByGenderAge@gender nvarchar(10) [='男'],@age int [=30]asselect * from MyStudent where FGender=@gender and FAge=@age-- 2 执行存储过程:exec usp_StudentByGenderAge -- 调用默认的参数exec usp_StudentByGenderAge '女',50 -- 调用自己指定的参数exec usp_StudentByGenderAge @age=50,@gender='女' -- 或者指定变量名
案例:带输出参数的存储过程
-- 1 定义存储过程:create proc usp_StudentByGenderAge@gender nvarchar(10) [='男'],@age int [=30],@recorderCount int output --加output表示该参数是需要在存储过程中赋值并返回的asselect * from MyStudent where FGender=@gender and FAge=@ageset @recorderCount=(select count(*) from MyStudent where FGender=@gender and FAge=@age)-- 2 执行存储过程:declare @count intexec usp_StudentByGenderAge @recorderCount=@count outputprint @count
output参数的目的,就是调用者需要传递一个变量进来,然后在存储过程中为该变量完成赋值工作,存储过程执行完成以后,将执行的对应结果返回给传递进来的变量
文章转载自全栈精英,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




