您的位置:首页 > 数据库

SQL Server 存储过程

2015-02-27 21:12 113 查看

SQLServer存储过程

Transact-SQL中的存储过程,非常类似于Java语言中的方法,它可以重复调用。当存储过程执行一次后,可以将语句缓存中,这样下次执行的时候直接使用缓存中的语句。这样就可以提高存储过程的性能。

Ø存储过程的概念

存储过程Procedure是一组为了完成特定功能的SQL语句集合,经编译后存储在数据库中,用户通过指定存储过程的名称并给出参数来执行。

存储过程中可以包含逻辑控制语句和数据操纵语句,它可以接受参数、输出参数、返回单个或多个结果集以及返回值。

由于存储过程在创建时即在数据库服务器上进行了编译并存储在数据库中,所以存储过程运行要比单个的SQL语句块要快。同时由于在调用时只需用提供存储过程名和必要的参数信息,所以在一定程度上也可以减少网络流量、简单网络负担。

1、存储过程的优点

A、存储过程允许标准组件式编程

存储过程创建后可以在程序中被多次调用执行,而不必重新编写该存储过程的SQL语句。而且数据库专业人员可以随时对存储过程进行修改,但对应用程序源代码却毫无影响,从而极大的提高了程序的可移植性。

B、存储过程能够实现较快的执行速度

如果某一操作包含大量的T-SQL语句代码,分别被多次执行,那么存储过程要比批处理的执行速度快得多。因为存储过程是预编译的,在首次运行一个存储过程时,查询优化器对其进行分析、优化,并给出最终被存在系统表中的存储计划。而批处理的T-SQL语句每次运行都需要预编译和优化,所以速度就要慢一些。

C、存储过程减轻网络流量

对于同一个针对数据库对象的操作,如果这一操作所涉及到的T-SQL语句被组织成一存储过程,那么当在客户机上调用该存储过程时,网络中传递的只是该调用语句,否则将会是多条SQL语句。从而减轻了网络流量,降低了网络负载。

D、存储过程可被作为一种安全机制来充分利用

系统管理员可以对执行的某一个存储过程进行权限限制,从而能够实现对某些数据访问的限制,避免非授权用户对数据的访问,保证数据的安全。

Ø系统存储过程

系统存储过程是系统创建的存储过程,目的在于能够方便的从系统表中查询信息或完成与更新数据库表相关的管理任务或其他的系统管理任务。系统存储过程主要存储在master数据库中,以“sp”下划线开头的存储过程。尽管这些系统存储过程在master数据库中,但我们在其他数据库还是可以调用系统存储过程。有一些系统存储过程会在创建新的数据库的时候被自动创建在当前数据库中。

常用系统存储过程有:

[code]execsp_databases;--查看数据库
execsp_tables;--查看表
execsp_columnsstudent;--查看列
execsp_helpIndexstudent;--查看索引
execsp_helpConstraintstudent;--约束
execsp_stored_procedures;
execsp_helptext'sp_stored_procedures';--查看存储过程创建、定义语句
execsp_renamestudent,stuInfo;--修改表、索引、列的名称
execsp_renamedbmyTempDB,myDB;--更改数据库名称
execsp_defaultdb'master','myDB';--更改登录名的默认数据库
execsp_helpdb;--数据库帮助,查询数据库信息
execsp_helpdbmaster;

[/code]
系统存储过程示例:

[code]--表重命名
execsp_rename'stu','stud';
select*fromstud;
--列重命名
execsp_rename'stud.name','sName','column';
execsp_help'stud';
--重命名索引
execsp_renameN'student.idx_cid',N'idx_cidd',N'index';
execsp_help'student';

--查询所有存储过程
select*fromsys.objectswheretype='P';
select*fromsys.objectswheretype_desclike'%pro%'andnamelike'sp%';

[/code]

Ø用户自定义存储过程

1、创建语法

[code]createproc|procedurepro_name
[{@参数数据类型}[=默认值][output],
{@参数数据类型}[=默认值][output],
....
]
as
SQL_statements

[/code]

2、创建不带参数存储过程

[code]--创建存储过程
if(exists(select*fromsys.objectswherename='proc_get_student'))
dropprocproc_get_student
go
createprocproc_get_student
as
select*fromstudent;

--调用、执行存储过程
execproc_get_student;

[/code]
3、修改存储过程

[code]--修改存储过程
alterprocproc_get_student
as
select*fromstudent;

[/code]
4、带参存储过程

[code]--带参存储过程
if(object_id('proc_find_stu','P')isnotnull)
dropprocproc_find_stu
go
createprocproc_find_stu(@startIdint,@endIdint)
as
select*fromstudentwhereidbetween@startIdand@endId
go

execproc_find_stu2,4;

[/code]
5、带通配符参数存储过程

[code]--带通配符参数存储过程
if(object_id('proc_findStudentByName','P')isnotnull)
dropprocproc_findStudentByName
go
createprocproc_findStudentByName(@namevarchar(20)='%j%',@nextNamevarchar(20)='%')
as
select*fromstudentwherenamelike@nameandnamelike@nextName;
go

execproc_findStudentByName;
execproc_findStudentByName'%o%','t%';

[/code]
6、带输出参数存储过程

[code]if(object_id('proc_getStudentRecord','P')isnotnull)
dropprocproc_getStudentRecord
go
createprocproc_getStudentRecord(
@idint,--默认输入参数
@namevarchar(20)out,--输出参数
@agevarchar(20)output--输入输出参数
)
as
select@name=name,@age=agefromstudentwhereid=@idandsex=@age;
go

--
declare@idint,
@namevarchar(20),
@tempvarchar(20);
set@id=7;
set@temp=1;
execproc_getStudentRecord@id,@nameout,@tempoutput;
select@name,@temp;
print@name+'#'+@temp;

[/code]

7、不缓存存储过程


[code]--WITHRECOMPILE不缓存
if(object_id('proc_temp','P')isnotnull)
dropprocproc_temp
go
createprocproc_temp
withrecompile
as
select*fromstudent;
go

execproc_temp;

[/code]
8、加密存储过程


[code]--加密WITHENCRYPTION
if(object_id('proc_temp_encryption','P')isnotnull)
dropprocproc_temp_encryption
go
createprocproc_temp_encryption
withencryption
as
select*fromstudent;
go

execproc_temp_encryption;
execsp_helptext'proc_temp';
execsp_helptext'proc_temp_encryption';

[/code]
9、带游标参数存储过程


[code]if(object_id('proc_cursor','P')isnotnull)
dropprocproc_cursor
go
createprocproc_cursor
@curcursorvaryingoutput
as
set@cur=cursorforward_onlystaticfor
selectid,name,agefromstudent;
open@cur;
go
--调用
declare@exec_curcursor;
declare@idint,
@namevarchar(20),
@ageint;
execproc_cursor@cur=@exec_curoutput;--调用存储过程
fetchnextfrom@exec_curinto@id,@name,@age;
while(@@fetch_status=0)
begin
fetchnextfrom@exec_curinto@id,@name,@age;
print'id:'+convert(varchar,@id)+',name:'+@name+',age:'+convert(char,@age);
end
close@exec_cur;
deallocate@exec_cur;--删除游标

[/code]

10、分页存储过程


[code]---存储过程、row_number完成分页
if(object_id('pro_page','P')isnotnull)
dropprocproc_cursor
go
createprocpro_page
@startIndexint,
@endIndexint
as
selectcount(*)fromproduct
;
select*from(
selectrow_number()over(orderbypid)asrowId,*fromproduct
)temp
wheretemp.rowIdbetween@startIndexand@endIndex
go
--dropprocpro_page
execpro_page1,4
--
--分页存储过程
if(object_id('pro_page','P')isnotnull)
dropprocpro_stu
go
createprocedurepro_stu(
@pageIndexint,
@pageSizeint
)
as
declare@startRowint,@endRowint
set@startRow=(@pageIndex-1)*@pageSize+1
set@endRow=@startRow+@pageSize-1
select*from(
select*,row_number()over(orderbyidasc)asnumberfromstudent
)t
wheret.numberbetween@startRowand@endRow;

execpro_stu2,2;

[/code]

ØRaiserror

Raiserror返回用户定义的错误信息,可以指定严重级别,设置系统变量记录所发生的错误。

语法如下:


[code]Raiserror({msg_id|msg_str|@local_variable}
{,severity,state}
[,argument[,…n]]
[withoption[,…n]]
)

[/code]
#msg_id:在sysmessages系统表中指定的用户定义错误信息

#msg_str:用户定义的信息,信息最大长度在2047个字符。

#severity:用户定义与该消息关联的严重级别。当使用msg_id引发使用sp_addmessage创建的用户定义消息时,raiserror上指定严重性将覆盖sp_addmessage中定义的严重性。

任何用户可以指定0-18直接的严重级别。只有sysadmin固定服务器角色常用或具有altertrace权限的用户才能指定19-25直接的严重级别。19-25之间的安全级别需要使用withlog选项。

#state:介于1至127直接的任何整数。State默认值是1。


[code]raiserror('iserror',16,1);
select*fromsys.messages;
--使用sysmessages中定义的消息
raiserror(33003,16,1);
raiserror(33006,16,1);


[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: