VB与SQL Server 存储过程
目录
一、SQL Server 存储过程
Transact-SQL中的存储过程,非常类似于Java语言中的方法,它可以重复调用。当存储过程执行一次后,可以将语句缓存中,这样下次执行的时候直接使用缓存中的语句。这样就可以提高存储过程的性能。
Ø 存储过程的概念
存储过程Procedure是一组为了完成特定功能的SQL语句集合,经编译后存储在数据库中,用户通过指定存储过程的名称并给出参数来执行。
存储过程中可以包含逻辑控制语句和数据操纵语句,它可以接受参数、输出参数、返回单个或多个结果集以及返回值。
由于存储过程在创建时即在数据库服务器上进行了编译并存储在数据库中,所以存储过程运行要比单个的SQL语句块要快。同时由于在调用时只需用提供存储过程名和必要的参数信息,所以在一定程度上也可以减少网络流量、简单网络负担。
Ø 存储过程的优点
A、 存储过程允许标准组件式编程
存储过程创建后可以在程序中被多次调用执行,而不必重新编写该存储过程的SQL语句。而且数据库专业人员可以随时对存储过程进行修改,但对应用程序源代码却毫无影响,从而极大的提高了程序的可移植性。
B、 存储过程能够实现较快的执行速度
如果某一操作包含大量的T-SQL语句代码,分别被多次执行,那么存储过程要比批处理的执行速度快得多。因为存储过程是预编译的,在首次运行一个存储过程时,查询优化器对其进行分析、优化,并给出最终被存在系统表中的存储计划。而批处理的T-SQL语句每次运行都需要预编译和优化,所以速度就要慢一些。
C、 存储过程减轻网络流量
对于同一个针对数据库对象的操作,如果这一操作所涉及到的T-SQL语句被组织成一存储过程,那么当在客户机上调用该存储过程时,网络中传递的只是该调用语句,否则将会是多条SQL语句。从而减轻了网络流量,降低了网络负载。
D、 存储过程可被作为一种安全机制来充分利用
系统管理员可以对执行的某一个存储过程进行权限限制,从而能够实现对某些数据访问的限制,避免非授权用户对数据的访问,保证数据的安全。
Ø 系统存储过程
系统存储过程是系统创建的存储过程,目的在于能够方便的从系统表中查询信息或完成与更新数据库表相关的管理任务或其他的系统管理任务。系统存储过程主要存储在master数据库中,以“sp”下划线开头的存储过程。尽管这些系统存储过程在master数据库中,但我们在其他数据库还是可以调用系统存储过程。有一些系统存储过程会在创建新的数据库的时候被自动创建在当前数据库中。
常用系统存储过程有:
1 2 3 4 5 6 7 8 9 10 11 12 |
exec sp_databases; --查看数据库 exec sp_tables; --查看表 exec sp_columns student;--查看列 exec sp_helpIndex student;--查看索引 exec sp_helpConstraint student;--约束 exec sp_stored_procedures; exec sp_helptext 'sp_stored_procedures';--查看存储过程创建、定义语句 exec sp_rename student, stuInfo;--修改表、索引、列的名称 exec sp_renamedb myTempDB, myDB;--更改数据库名称 exec sp_defaultdb 'master', 'myDB';--更改登录名的默认数据库 exec sp_helpdb;--数据库帮助,查询数据库信息 exec sp_helpdb master; |
系统存储过程示例:
1 2 3 4 5 6 7 8 9 10 11 12 |
--表重命名 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 4 5 6 7 |
create proc | procedure pro_name [{@参数数据类型} [=默认值] [output], {@参数数据类型} [=默认值] [output], .... ] as SQL_statements |
2、 创建不带参数存储过程
1 2 3 4 5 6 7 |
--创建存储过程 if (exists (select * from sys.objects where name = 'proc_get_student')) drop proc proc_get_student go create proc proc_get_student as select * from student; |
1 2 |
--调用、执行存储过程 exec proc_get_student; |
3、 修改存储过程
1 2 3 4 |
--修改存储过程 alter proc proc_get_student as select * from student; |
4、 带参存储过程
1 2 3 4 5 6 7 8 |
--带参存储过程 if (object_id('proc_find_stu', 'P') is not null) drop proc proc_find_stu go create proc proc_find_stu(@startId int, @endId int) as select * from student where id between @startId and @endId go |
1 2 |
--调用、执行存储过程 exec proc_find_stu 2, 4; |
5、 带通配符参数存储过程
1 2 3 4 5 6 7 8 |
--带通配符参数存储过程 if (object_id('proc_findStudentByName', 'P') is not null) drop proc proc_findStudentByName go create proc proc_findStudentByName(@name varchar(20) = '%j%', @nextName varchar(20) = '%') as select * from student where name like @name and name like @nextName; go |
1 2 3 |
--调用、执行存储过程 exec proc_findStudentByName; exec proc_findStudentByName '%o%', 't%'; |
6、 带输出参数存储过程
1 2 3 4 5 6 7 8 9 10 11 |
if (object_id('proc_getStudentRecord', 'P') is not null) drop proc proc_getStudentRecord go create proc proc_getStudentRecord( @id int, --默认输入参数 @name varchar(20) out, --输出参数 @age varchar(20) output--输入输出参数 ) as select @name = name, @age = age from student where id = @id and sex = @age; go |
1 2 3 4 5 6 7 8 9 |
--调用、执行存储过程 declare @id int, @name varchar(20), @temp varchar(20); set @id = 7; set @temp = 1; exec proc_getStudentRecord @id, @name out, @temp output; select @name, @temp; print @name + '#' + @temp; |
7、 不缓存存储过程
1 2 3 4 5 6 7 8 9 |
--WITH RECOMPILE 不缓存 if (object_id('proc_temp', 'P') is not null) drop proc proc_temp go create proc proc_temp with recompile as select * from student; go |
1 2 |
--调用、执行存储过程 exec proc_temp; |
8、 加密存储过程
1 2 3 4 5 6 7 8 9 |
--加密WITH ENCRYPTION if (object_id('proc_temp_encryption', 'P') is not null) drop proc proc_temp_encryption go create proc proc_temp_encryption with encryption as select * from student; go |
1 2 3 4 |
--调用、执行存储过程 exec proc_temp_encryption; exec sp_helptext 'proc_temp'; exec sp_helptext 'proc_temp_encryption'; |
9、 带游标参数存储过程
1 2 3 4 5 6 7 8 9 10 |
if (object_id('proc_cursor', 'P') is not null) drop proc proc_cursor go create proc proc_cursor @cur cursor varying output as set @cur = cursor forward_only static for select id, name, age from student; open @cur; go |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
--调用 declare @exec_cur cursor; declare @id int, @name varchar(20), @age int; exec proc_cursor @cur = @exec_cur output;--调用存储过程 fetch next from @exec_cur into @id, @name, @age; while (@@fetch_status = 0) begin fetch next from @exec_cur into @id, @name, @age; print 'id: ' + convert(varchar, @id) + ', name: ' + @name + ', age: ' + convert(char, @age); end close @exec_cur; deallocate @exec_cur;--删除游标 |
10、 分页存储过程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
---存储过程、row_number完成分页 if (object_id('pro_page', 'P') is not null) drop proc proc_cursor go create proc pro_page @startIndex int, @endIndex int as select count(*) from product ; select * from ( select row_number() over(order by pid) as rowId, * from product ) temp where temp.rowId between @startIndex and @endIndex go --drop proc pro_page exec pro_page 1, 4 -- --分页存储过程 if (object_id('pro_page', 'P') is not null) drop proc pro_stu go create procedure pro_stu( @pageIndex int, @pageSize int ) as declare @startRow int, @endRow int set @startRow = (@pageIndex - 1) * @pageSize +1 set @endRow = @startRow + @pageSize -1 select * from ( select *, row_number() over (order by id asc) as number from student ) t where t.number between @startRow and @endRow; |
1 |
exec pro_stu 2, 2; |
Ø Raiserror
Raiserror返回用户定义的错误信息,可以指定严重级别,设置系统变量记录所发生的错误。
语法如下:
1 2 3 4 5 |
Raiserror({msg_id | msg_str | @local_variable} {, severity, state} [,argument[,…n]] [with option[,…n]] ) |
# msg_id:在sysmessages系统表中指定的用户定义错误信息
# msg_str:用户定义的信息,信息最大长度在2047个字符。
# severity:用户定义与该消息关联的严重级别。当使用msg_id引发使用sp_addmessage创建的用户定义消息时,raiserror上指定严重性将覆盖sp_addmessage中定义的严重性。
任何用户可以指定0-18直接的严重级别。只有sysadmin固定服务器角色常用或具有alter trace权限的用户才能指定19-25直接的严重级别。19-25之间的安全级别需要使用with log选项。
# state:介于1至127直接的任何整数。State默认值是1。
1 2 3 4 5 |
raiserror('is error', 16, 1); select * from sys.messages; --使用sysmessages中定义的消息 raiserror(33003, 16, 1); raiserror(33006, 16, 1); |
二、VB连接存储过程
通过ADO Command 对象连接SQL的存储过程。
Command 对象
ADO Command 对象用于执行面向数据库的一次简单查询。此查询可执行诸如创建、添加、取回、删除或更新记录等动作。
如果该查询用于取回数据,此数据将以一个 RecordSet 对象返回。这意味着被取回的数据能够被 RecordSet 对象的属性、集合、方法或事件进行操作。
Command 对象的主要特性是有能力使用存储查询和带有参数的存储过程。
ProgID
1 |
set objCommand=Server.CreateObject("ADODB.command") |
属性
属性 | 描述 |
---|---|
ActiveConnection | 设置或返回包含了定义连接或 Connection 对象的字符串。 |
CommandText | 设置或返回包含提供者(provider)命令(如 SOL 语句、表格名称或存储的过程调用)的字符串值。默认值为 ""(零长度字符串)。 |
CommandTimeout | 设置或返回长整型值,该值指示等待命令执行的时间(单位为秒)。默认值为 30。 |
CommandType | 设置或返回一个 Command 对象的类型 |
Name | 设置或返回一个 Command 对象的名称 |
Prepared | 指示执行前是否保存命令的编译版本(已经准备好的版本)。 |
State | 返回一个值,此值可描述该 Command 对象处于打开、关闭、连接、执行还是取回数据的状态。 |
方法
方法 | 描述 |
---|---|
Cancel | 取消一个方法的一次执行。 |
CreateParameter | 创建一个新的 Parameter 对象 |
Execute | 执行 CommandText 属性中的查询、SQL 语句或存储过程。 |
集合
集合 | 描述 |
---|---|
Parameters | 包含一个 Command 对象的所有 Parameter 对象。 |
Properties | 包含一个 Command 对象的所有 Property 对象。 |
示例
假设有一个名为doc_ProcName存储过程,该存储过程有一个输入参数,一个输出参数。
1) 直接传递参数调用存储过程(未测试成功)
直接传递参数方法主要通过以下几个步骤来实现:
(1) 通过ADODB的Connection对象打开与数据源的连接;
(2) 通过ActiveConnection指定Command对象当前所属的Connection对象;
(3) 通过CommandText属性设置Command对象的源,即要调用的存储过程;
(4) 通过CommandType属性确定Command对象的源类型,如果源类型为存储过程CommandType即为adCmdStoredProc;
(5) 通过Command对象的Parameters集合向所调用的存储过程传递参数,其中对象Parameters(0)为执行存储过程的返回值,返回值为0则执行存储过程成功;
(6) 通过Eexecute方法执行在 CommandText 属性中指定的存储过程。
以存储过程doc_ProcName为例,关键代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Dim strS As String '定义一变量 Dim adoconn As New ADODB.Connection 'Connection 对象代表了打开与数据源的连接。 Dim adocomm As New ADODB.Command 'Command 对象定义了将对数据源执行的指定命令。 Dim ReturnValue As Integer '调用存储过程的返回值 adoconn.ConnectionString = Adodc1.ConnectionString 'Adodc1为窗体中的ADO控件,并已成功连接数据库 adoconn.Open Set adocomm.ActiveConnection = adoconn '指示指定的 Command对象当前所属的 Connection对象。 adocomm.CommandText = "doc_ProcName" '设置Command对象源。 adocomm.CommandType = adCmdStoredProc '通知提供者CommandText属性有什么,它可能包括Command对象的源类型。设置这个属性优化了该命令的执行。 adocomm.Parameters(1) = "1" adocomm.Parameters(2) = "OutputParameters" 'OutputParameters可以为任意的字符串或数字 adocomm.Execute ReturnValue = adocomm.Parameters(0) '存储过程的返回值,返回0则成功执行。 strS = adocomm.Parameters(2) '把存储过程的输出参数的值赋给变量strS |
2) 追加参数法调用存储过程
追加参数通过CreateParameter方法,用来指定属性创建新的Parameter对象。具体语法如下:
1 |
Set parameter = command.CreateParameter (Name, Type, Direction, Size, Value) |
·Name 可选,字符串,代表 Parameter 对象名称。
·Type 可选,长整型值,指定 Parameter 对象数据类型。
·Direction 可选,长整型值,指定 Parameter 对象类型。
·Size 可选,长整型值,指定参数值最大长度(以字符或字节数为单位)。
·Value 可选,变体型,指定 Parameter 对象值。
这种方法与上面一种方法的分别主要在于,追加参数的方法在向存储过程传递参数时,这种方法首先通过CreateParameter方法为存储过程创建参数,然后通过Append方法将创建的参数追加到Parameters集合中去。
仍然以存储过程doc_ProcName的调用为例,关键代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Dim mRst As ADODB.Recordset 'Recordset 对象表示的是来自基本表或命令执行结果的记录全集。 Dim prm As ADODB.Parameter 'Parameter 对象代表参数或与基于参数化查询或存储过程的Command 对象相关联的参数。 adoconn.ConnectionString = Adodc1.ConnectionString adoconn.Open Set adocomm.ActiveConnection = adoconn adocomm.CommandText = "doc_ProcName" adocomm.CommandType = adCmdStoredProc Set prm = adocomm.CreateParameter("parameter1", adTinyInt, adParamInput, , "1") adocomm.Parameters.Append prm Set prm = adocomm.CreateParameter("parameter2", adInteger, adParamOutput) adocomm.Parameters.Append prm Set mRst = adocomm.Execute ReturnValue = adocomm.Parameters(0) |