创建存储过程:
一、
create + proc + 名字(参数1 参数1类型,参数2 参数2类型)
as
查询语句(例如:select+from+where)
go
例:
create proc pr_stu_marks
as
select StuInfo.stuid,stuName,subject,score
from StuInfo,StuMarks
where StuInfo.stuid=StuMarks.stuid
go
exec dbo.pr_stu_marks
二、
exec + 存储名称 (有参数的可以在括号里写值)
【存储名称的查找: 数据库名→可编辑性→存储过程→存储名称】
例:
exec dbo.pr_stu_marks '张三'
下面整理的这组代码是:如果传入姓名,则查询执行学生;否则查询全部
create proc pr_stu_marks(@name varchar(10)=null)
as
if @name is null
begin
select StuInfo.stuid,stuName,subject,score
from StuInfo,StuMarks
where StuInfo.stuid=StuMarks.stuid
end
else
begin
select StuInfo.stuid,stuName,subject,score
from StuInfo,StuMarks
where StuInfo.stuid=StuMarks.stuid and stuName=@name
end
go
exec dbo.pr_stu_marks '张三'
三、查询存储过程中的错误。
/*--使用RAISERROR语句抛出错误信息--*/
--RAISERROR (错误消息, 严重级别, 状态)
--自定义错误
例:
create proc devide(@a int,@b int,@c int output)
as
if(@b=0)
begin
raiserror('0不能作为除数',10,2)
set @c=0
end
else
begin
set @c=@a/@b
end
go
declare @c int
exec devide 3,0,@c output
print @c
输出结果为(print是文本形式):0不能作为除数
0