SQL Server 存储过程

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

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

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

1、 存储过程的优点 

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

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

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

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

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

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

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

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

Ø 系统存储过程 

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

    常用系统存储过程有: 

 1 exec sp_databases; --查看数据库
 2 exec sp_tables;        --查看表
 3 exec sp_columns student;--查看列
 4 exec sp_helpIndex student;--查看索引
 5 exec sp_helpConstraint student;--约束
 6 exec sp_stored_procedures;
 7 exec sp_helptext 'sp_stored_procedures';--查看存储过程创建、定义语句
 8 exec sp_rename student, stuInfo;--修改表、索引、列的名称
 9 exec sp_renamedb myTempDB, myDB;--更改数据库名称
10 exec sp_defaultdb 'master', 'myDB';--更改登录名的默认数据库
11 exec sp_helpdb;--数据库帮助,查询数据库信息
12 exec sp_helpdb master;
系统存储过程示例: 

--表重命名
exec sp_rename 'stu', 'stud';
select * from stud;
--列重命名
exec sp_rename 'stud.name', 'sName', 'column';
exec sp_help 'stud';
--重命名索引
exec sp_rename N'student.idx_cid', N'idx_cidd', N'index';
exec sp_help 'student';

--查询所有存储过程
select * from sys.objects where type = 'P';
select * from sys.objects where type_desc like '%pro%' and name like 'sp%';

 

Ø 用户自定义存储过程 

  

  1  1、 创建语法 
  2 
  3 create proc | procedure pro_name
  4     [{@参数数据类型} [=默认值] [output],
  5      {@参数数据类型} [=默认值] [output],
  6      ....
  7     ]
  8 as
  9     SQL_statements
 10 
 11   
 12 
 13    2、 创建不带参数存储过程 
 14 
 15 --创建存储过程
 16 if (exists (select * from sys.objects where name = 'proc_get_student'))
 17     drop proc proc_get_student
 18 go
 19 create proc proc_get_student
 20 as
 21     select * from student;
 22 
 23 --调用、执行存储过程
 24 exec proc_get_student;
 25 
 26 
 27    3、 修改存储过程 
 28 
 29 --修改存储过程
 30 alter proc proc_get_student
 31 as
 32 select * from student;
 33 
 34 
 35    4、 带参存储过程 
 36 
 37 --带参存储过程
 38 if (object_id('proc_find_stu', 'P') is not null)
 39     drop proc proc_find_stu
 40 go
 41 create proc proc_find_stu(@startId int, @endId int)
 42 as
 43     select * from student where id between @startId and @endId
 44 go
 45 
 46 exec proc_find_stu 2, 4;
 47 
 48 
 49    5、 带通配符参数存储过程 
 50 
 51 --带通配符参数存储过程
 52 if (object_id('proc_findStudentByName', 'P') is not null)
 53     drop proc proc_findStudentByName
 54 go
 55 create proc proc_findStudentByName(@name varchar(20) = '%j%', @nextName varchar(20) = '%')
 56 as
 57     select * from student where name like @name and name like @nextName;
 58 go
 59 
 60 exec proc_findStudentByName;
 61 exec proc_findStudentByName '%o%', 't%';
 62 
 63 
 64    6、 带输出参数存储过程 
 65 
 66 if (object_id('proc_getStudentRecord', 'P') is not null)
 67     drop proc proc_getStudentRecord
 68 go
 69 create proc proc_getStudentRecord(
 70     @id int, --默认输入参数
 71     @name varchar(20) out, --输出参数
 72     @age varchar(20) output--输入输出参数
 73 )
 74 as
 75     select @name = name, @age = age  from student where id = @id and sex = @age;
 76 go
 77 
 78 -- 
 79 declare @id int,
 80         @name varchar(20),
 81         @temp varchar(20);
 82 set @id = 7; 
 83 set @temp = 1;
 84 exec proc_getStudentRecord @id, @name out, @temp output;
 85 select @name, @temp;
 86 print @name + '#' + @temp;
 87 
 88 
 89 
 90 
 91 
 92    7、 不缓存存储过程 
 93 
 94 --WITH RECOMPILE 不缓存
 95 if (object_id('proc_temp', 'P') is not null)
 96     drop proc proc_temp
 97 go
 98 create proc proc_temp
 99 with recompile
100 as
101     select * from student;
102 go
103 
104 exec proc_temp;
105 
106 
107    8、 加密存储过程 
108 
109 --加密WITH ENCRYPTION 
110 if (object_id('proc_temp_encryption', 'P') is not null)
111     drop proc proc_temp_encryption
112 go
113 create proc proc_temp_encryption
114 with encryption
115 as
116     select * from student;
117 go
118 
119 exec proc_temp_encryption;
120 exec sp_helptext 'proc_temp';
121 exec sp_helptext 'proc_temp_encryption';
122 
123 
124    9、 带游标参数存储过程 
125 
126 if (object_id('proc_cursor', 'P') is not null)
127     drop proc proc_cursor
128 go
129 create proc proc_cursor
130     @cur cursor varying output
131 as
132     set @cur = cursor forward_only static for
133     select id, name, age from student;
134     open @cur;
135 go
136 --调用
137 declare @exec_cur cursor;
138 declare @id int,
139         @name varchar(20),
140         @age int;
141 exec proc_cursor @cur = @exec_cur output;--调用存储过程
142 fetch next from @exec_cur into @id, @name, @age;
143 while (@@fetch_status = 0)
144 begin
145     fetch next from @exec_cur into @id, @name, @age;
146     print 'id: ' + convert(varchar, @id) + ', name: ' + @name + ', age: ' + convert(char, @age);
147 end
148 close @exec_cur;
149 deallocate @exec_cur;--删除游标
150 
151 
152 
153 
154 
155    10、 分页存储过程 
156 
157 ---存储过程、row_number完成分页
158 if (object_id('pro_page', 'P') is not null)
159     drop proc proc_cursor
160 go
161 create proc pro_page
162     @startIndex int,
163     @endIndex int
164 as
165     select count(*) from product
166 ;    
167     select * from (
168         select row_number() over(order by pid) as rowId, * from product 
169     ) temp
170     where temp.rowId between @startIndex and @endIndex
171 go
172 --drop proc pro_page
173 exec pro_page 1, 4
174 --
175 --分页存储过程
176 if (object_id('pro_page', 'P') is not null)
177     drop proc pro_stu
178 go
179 create procedure pro_stu(
180     @pageIndex int,
181     @pageSize int
182 )
183 as
184     declare @startRow int, @endRow int
185     set @startRow = (@pageIndex - 1) * @pageSize +1
186     set @endRow = @startRow + @pageSize -1
187     select * from (
188         select *, row_number() over (order by id asc) as number from student 
189     ) t
190     where t.number between @startRow and @endRow;
191 
192 exec pro_stu 2, 2;
193 
194 
195 
196 
197 
198 
199 Ø Raiserror 
200 
201 Raiserror返回用户定义的错误信息,可以指定严重级别,设置系统变量记录所发生的错误。 
202 
203    语法如下: 
204 
205 Raiserror({msg_id | msg_str | @local_variable}
206   {, severity, state}
207   [,argument[,…n]]
208   [with option[,…n]]
209 )
210 
211 
212    # msg_id:在sysmessages系统表中指定的用户定义错误信息 
213 
214    # msg_str:用户定义的信息,信息最大长度在2047个字符。 
215 
216    # severity:用户定义与该消息关联的严重级别。当使用msg_id引发使用sp_addmessage创建的用户定义消息时,raiserror上指定严重性将覆盖sp_addmessage中定义的严重性。 
217 
218     任何用户可以指定0-18直接的严重级别。只有sysadmin固定服务器角色常用或具有alter trace权限的用户才能指定19-25直接的严重级别。19-25之间的安全级别需要使用with log选项。 
219 
220    # state:介于1至127直接的任何整数。State默认值是1。 
221 
222 raiserror('is error', 16, 1);
223 select * from sys.messages;
224 --使用sysmessages中定义的消息
225 raiserror(33003, 16, 1);
226 raiserror(33006, 16, 1);

 

【转自】http://www.cnblogs.com/hoojo/archive/2011/07/19/2110862.html

posted on 2015-07-21 10:31  弓长*  阅读(143)  评论(0编辑  收藏  举报

导航