ASP Application Development Keys stored procedure

 ASP and stored procedure (Stored Procedures) article a lot, but I doubt whether the authors actually practiced. I had access to a lot of relevant information at the beginner, found many ways in which to provide the actual operation is not the case. For simple applications, such information may be helpful, but limited, because they simply stereotyped, copying each other, slightly more complex application, did not elaborate on all the.

  Now, I basically accessed by calling a stored procedure SQL Server, the following text is a summary of the practice, we want to be able to help.

  Procedure is stored as an executable object in the database stored in one or more SQL commands.

  The definition is always very abstract. Storage process is actually able to complete certain operations of a set of SQL statements, but this set of statements is placed in the database (Here we only talk about SQL Server). If we by creating stored procedures and call stored procedures in ASP, SQL statements can be avoided with the ASP code mixed together. The advantage of this at least three:

  First, greatly improving efficiency. The stored procedure execution itself is very fast, and call stored procedures can greatly reduce the number of interactions with the database.

  Second, to improve the safety of. If you mix SQL statements in the ASP code, once the code is compromised, the library structure also means compromised.

  Third, to reuse SQL statements.

  In the ASP, the general command object calls a stored procedure, depending on the circumstances, other paper also describes a method call. For convenience of explanation, the input and output in accordance with the stored procedure, for the simple classification:

  1. Only a single stored procedure returns the record set

  Consider the following stored procedure (not the purpose of this paper describes T-SQL syntax, the code for the stored procedure is given only , not stated):

/*SP1*/
CREATE PROCEDURE dbo.getUserList
as
set nocount on
begin
select * from dbo.[userinfo]
end
go

  More storage process takes all records userinfo table, return a record set. ASP code stored procedure call by the command object is as follows:

'** Command object by calling a stored procedure **
the DIM MyComm, MyRst
the Set MyComm = Server.CreateObject ( "the ADODB.Command")
MyComm.ActiveConnection = MyConStr' MyConStr database connection string
MyComm.CommandText = "getUserList" 'designated storage procedure name
MyComm.CommandType = 4 'shows that this is a stored procedure
MyComm.Prepared = true' requirements will be precompiled SQL commands
the Set MyRst = MyComm.Execute
the Set MyComm = Nothing

  Acquired set of records stored procedure assigns MyRst, next, can be operated MyRst.

  In the above code, the CommandType attribute indicates the type of request, and the values described as follows:

  -1 indicates the type of the parameter can not be determined CommandText
  1 shows a general type of command CommandText
  2 indicate the presence of a CommandText parameter table name is
  4 shows that the parameter is CommandText the name of a stored procedure

  can also Recordset Connection object or objects stored procedure call process are as follows:

'** Connection object by calling a stored procedure **
the DIM the MyConn, MyRst
the Set the MyConn = Server.CreateObject ( "ADODB.Connection")
MyConn.open MyConStr' MyConStr database connection string
Set MyRst = MyConn.Execute ( "getUserList" , 0,4) 'the same meaning as the last reference off the CommandType
the Set the MyConn = Nothing

' ** Recordset object by calling a stored procedure **
the DIM MyRst
the Set MyRst = Server.CreateObject ( "ADODB.Recordset")
MyRst.open "getUserList", MyConStr , 0,1,4
'MyConStr database connection string, the last one reference CommandType same meaning as off

  2. there is no input and output stored procedure

  Consider the following stored procedure:

/*SP2*/
CREATE PROCEDURE dbo.delUserAll
as
set nocount on
begin
delete from dbo.[userinfo]
end
go

  The stored procedure userinfo deleting records in the table, there is no input and an output, the above method calls have said substantially the same, except that no record set to obtain:

'** Command object by calling a stored procedure **
the DIM MyComm
the Set MyComm = Server.CreateObject ( "the ADODB.Command")
MyComm.ActiveConnection = MyConStr' MyConStr database connection string
MyComm.CommandText = "delUserAll" 'specifies the name of the stored procedure
MyComm.CommandType = 4 'shows that this is a stored procedure
MyComm.Prepared = true' requirements will be precompiled SQL command
MyComm.Execute 'here do not have to get record set
set MyComm = Nothing

  Of course, such a stored procedure can call the Connection object or Recordset object, but the establishment of Recordset object is to obtain records set in the case did not return record set, or use Command object it.

  3. The return value of a stored procedure

  during similar operations SP2 should make full use of SQL Server powerful transactional capabilities to maintain data consistency. And, we may need to return to the stored procedure execution, to that end, SP2 will be amended as follows:

/*SP3*/
CREATE PROCEDURE dbo.delUserAll
as
set nocount on
begin
BEGIN TRANSACTION
delete from dbo.[userinfo]
IF @@error=0
begin
COMMIT TRANSACTION
return 1
end
ELSE
begin
ROLLBACK TRANSACTION
return 0
end
return
end
go

  More storage process, delete the smooth implementation when, returns 1, otherwise it returns 0, and rollback. In order to obtain the return value in ASP, need to use Parameters collection to the statement parameters:

'**调用带有返回值的存储过程并取得返回值**
DIM MyComm,MyPara
Set MyComm = Server.CreateObject("ADODB.Command")
MyComm.ActiveConnection = MyConStr 'MyConStr是数据库连接字串
MyComm.CommandText = "delUserAll" '指定存储过程名
MyComm.CommandType = 4 '表明这是一个存储过程
MyComm.Prepared = true '要求将SQL命令先行编译
'声明返回值
Set Mypara = MyComm.CreateParameter("RETURN",2,4)
MyComm.Parameters.Append MyPara
MyComm.Execute
'取得返回值
DIM retValue
retValue = MyComm(0) '或retValue = MyComm.Parameters(0)
Set MyComm = Nothing

  In MyComm.CreateParameter ( "RETURN", 2,4), the meaning of each parameter are as follows:

  The first parameter ( "RETURE") is the parameter name. Parameter name can be set arbitrarily, but should generally be the same parameter name declared in the stored procedure. Here is the return value, I used the set to "RETURE";

  the second argument (2), indicates that the data type of the parameter, the specific type code, please refer to the ADO reference given below common types of code:

adBigInt: 20;
adBinary: 128;
adBoolean: 11;
adChar 129;
adDBTimeStamp: 135;
adEmpty: 0;
adInteger: 3;
adSmallInt: 2;
adTinyInt 16;
adVarChar: 200;

  For the return value, the shaping can take, and the value -1 to -99 reserved;

  third parameter (4), indicating the nature of the parameters, where 4 indicates that this is a return value. Description This parameter values as follows:

  0: type can not be determined; 1: Input parameters; 2: Input parameters; 3: input or output parameters; 4: Return value

  ASP code given above, it should be said that the complete code, That is the most complex code, in fact,

Set Mypara = MyComm.CreateParameter("RETURN",2,4)
MyComm.Parameters.Append MyPara

  It can be simplified to

MyComm.Parameters.Append MyComm.CreateParameter("RETURN",2,4)

  You can even continue to simplify, it will be explained later.

  For a stored procedure with parameters, you can only use the Command object call (also has information that can be invoked through the Connection object or Recordset object, but I did not try to be too).

 4. The input and output parameters of the stored procedure

  return value is actually a special output parameters. In most cases, we use stored procedures simultaneously input and output parameters, such as we want to get the user information table, a user ID of the user name, this time, there is a user ID input parameters ---- , and an output parameter ---- username. Accomplish this stored procedure is as follows:

/*SP4*/
CREATE PROCEDURE dbo.getUserName
@UserID int,
@UserName varchar(40) output
as
set nocount on
begin
if @UserID is null return
select @UserName=username
from dbo.[userinfo]
where userid=@UserID
return
end
go

  ASP code calls the stored procedure is as follows:

'**调用带有输入输出参数的存储过程**
DIM MyComm,UserID,UserName
UserID = 1
Set MyComm = Server.CreateObject("ADODB.Command")
MyComm.ActiveConnection = MyConStr 'MyConStr是数据库连接字串
MyComm.CommandText = "getUserName" '指定存储过程名
MyComm.CommandType = 4 '表明这是一个存储过程
MyComm.Prepared = true '要求将SQL命令先行编译
'声明参数
MyComm.Parameters.append MyComm.CreateParameter("@UserID",3,1,4,UserID)
MyComm.Parameters.append MyComm.CreateParameter("@UserName",200,2,40)
MyComm.Execute
'取得出参
UserName = MyComm(1)
Set MyComm = Nothing

  In the code above, it can be seen different values of the return statement, declaration requires five parameters input parameters, four parameters required output parameter is declared. When declaring input parameters are the five parameters: the parameter name, parameter data type, parameter types, the data length of parameter value. When you declare an output parameter, not the last parameter: parameter value.

  Special attention is required: the order in the parameter declaration, the order must be defined and stored procedure, and data type of each parameter, but also the same as defined length stored procedure.

  If the stored procedure has multiple parameters, ASP code seem complicated, simplify the code can be used with the command:

'** call a stored procedure with input and output parameters (simplified codes) **
the DIM MyComm, the UserID, UserName
the UserID. 1 =
the Set MyComm = Server.CreateObject ( "the ADODB.Command")
with MyComm
 .ActiveConnection = MyConStr' database MyConStr connection string
 .CommandText = "getUserName" 'specify the stored procedure name
 .CommandType = 4' shows that this is a stored procedure
 .Prepared = true 'requirements will be precompiled SQL command
 .Parameters.append .CreateParameter ( "@ UserID", 3, 1, 4, UserID)
 .Parameters.Append .CreateParameter ( "@ UserName", 200,2,40)
 .Execute
End with
UserName = MyComm (1)
the Set MyComm = Nothing

  If we are to make ID of 1 to 10,10 users of the user name, it is not to create a Command object 10 times it? no. If you need to repeatedly call the same stored procedure, simply by changing the input parameters, you will get different output:

'**多次调用同一存储过程**
DIM MyComm,UserID,UserName
UserName = ""
Set MyComm = Server.CreateObject("ADODB.Command")
for UserID = 1 to 10
 with MyComm
  .ActiveConnection = MyConStr 'MyConStr是数据库连接字串
  .CommandText = "getUserName" '指定存储过程名
  .CommandType = 4 '表明这是一个存储过程
  .Prepared = true '要求将SQL命令先行编译
  if UserID = 1 then
   .Parameters.append .CreateParameter("@UserID",3,1,4,UserID)
   .Parameters.append .CreateParameter("@UserName",200,2,40)
   .Execute
  else
   '重新给入参赋值(此时参数值不发生变化的入参以及出参不必重新声明)
   .Parameters("@UserID") = UserID
   .Execute
  end if
 end with
 UserName = UserName + MyComm (1) + "," ' Maybe you prefer to use an array to store
the Next
the Set MyComm = Nothing

  Code can be seen from the above: when stored call the same procedure was repeated, only for the input parameter value is changed to re-assignment, this is only one input parameter at a plurality of input and output parameters, and the value of each call when a change occurs, the code amount can be greatly reduced.

  5. At the same time having a return value, stored process input parameters, output parameters

  stated earlier, at the time of calling a stored procedure in the same order to declare the parameters defined in the stored procedure. Another point to pay particular attention to: if the stored procedure has both a return value and input and output parameters, return values to the first statement.

  To demonstrate the method call in this case, we improve the look of the example above. Or to obtain a user ID is 1 user names, but it is possible that the user does not exist (the user has deleted, and userid is the field from growing). The presence or absence of a user stored procedure to return a different value. At this time, the stored procedure and ASP code is as follows:

/*SP5*/
CREATE PROCEDURE dbo.getUserName
--为了加深对"顺序"的印象,将以下两参数的定义顺序颠倒一下
@UserName varchar(40) output,
@UserID int
as
set nocount on
begin
if @UserID is null return
select @UserName=username
from dbo.[userinfo]
where userid=@UserID
if @@rowcount>0
return 1
else
return 0
return
end
go

'**调用同时具有返回值、输入参数、输出参数的存储过程**
DIM MyComm,UserID,UserName
UserID = 1
Set MyComm = Server.CreateObject("ADODB.Command")
with MyComm
.ActiveConnection = MyConStr 'MyConStr是数据库连接字串
.CommandText = "getUserName" '指定存储过程名
.CommandType = 4 '表明这是一个存储过程
.Prepared = true '要求将SQL命令先行编译
'返回值要最先被声明
.Parameters.Append .CreateParameter("RETURN",2,4)
'以下两参数的声明顺序也做相应颠倒
.Parameters.append .CreateParameter("@UserName",200,2,40)
.Parameters.append .CreateParameter("@UserID",3,1,4,UserID)
.Execute
end with
if MyComm(0) = 1 then
UserName = MyComm(1)
else
UserName = "该用户不存在"
end if
Set MyComm = Nothing


  6. 同时返回参数和记录集的存储过程

  有时候,我们需要存储过程同时返回参数和记录集,比如在利用存储过程分页时,要同时返回记录集以及数据总量等参数。以下给出一个进行分页处理的存储过程:

/*SP6*/
CREATE PROCEDURE dbo.getUserList
@iPageCount int OUTPUT, --总页数
@iPage int, --当前页号
@iPageSize int --每页记录数
as
set nocount on
begin
--创建临时表
create table #t (ID int IDENTITY, --自增字段
userid int,
username varchar(40))
--向临时表中写入数据
insert into #t
select userid,username from dbo.[UserInfo]
order by userid

--取得记录总数
declare @iRecordCount int
set @iRecordCount = @@rowcount

--确定总页数
IF @iRecordCount%@iPageSize=0
SET @iPageCount=CEILING(@iRecordCount/@iPageSize)
ELSE
SET @iPageCount=CEILING(@iRecordCount/@iPageSize)+1

--若请求的页号大于总页数,则显示最后一页
IF @iPage > @iPageCount
SELECT @iPage = @iPageCount

--确定当前页的始末记录
DECLARE @iStart int --start record
DECLARE @iEnd int --end record
SELECT @iStart = (@iPage - 1) * @iPageSize
SELECT @iEnd = @iStart + @iPageSize + 1

--取当前页记录
select * from #t where ID>@iStart and ID<@iEnd

--删除临时表
DROP TABLE #t

--返回记录总数
return @iRecordCount
end
go


  在上面的存储过程中,输入当前页号及每页记录数,返回当前页的记录集,总页数及记录总数。为了更具典型性,将记录总数以返回值的形式返回。以下是调用该存储过程的ASP代码(具体的分页操作略去):

'**调用分页存储过程**
DIM pagenow,pagesize,pagecount,recordcount
DIM MyComm,MyRst
pagenow = Request("pn")
'自定义函数用于验证自然数
if CheckNar(pagenow) = false then pagenow = 1
pagesize = 20
Set MyComm = Server.CreateObject("ADODB.Command")
with MyComm
.ActiveConnection = MyConStr 'MyConStr是数据库连接字串
.CommandText = "getUserList" '指定存储过程名
.CommandType = 4 '表明这是一个存储过程
.Prepared = true '要求将SQL命令先行编译
'返回值(记录总量)
.Parameters.Append .CreateParameter("RETURN",2,4)
'出参(总页数)
.Parameters.Append .CreateParameter("@iPageCount",3,2)
'入参(当前页号)
.Parameters.append .CreateParameter("@iPage",3,1,4,pagenow)
'入参(每页记录数)
.Parameters.append .CreateParameter("@iPageSize",3,1,4,pagesize)
Set MyRst = .Execute
end with
if MyRst.state = 0 then '未取到数据,MyRst关闭
recordcount = -1
else
MyRst.close '注意:若要取得参数值,需先关闭记录集对象
recordcount = MyComm(0)
pagecount = MyComm(1)
if cint(pagenow)>=cint(pagecount) then pagenow=pagecount
end if
Set MyComm = Nothing

'以下显示记录
if recordcount = 0 then
Response.Write "无记录"
elseif recordcount > 0 then
MyRst.open
do until MyRst.EOF
......
loop
'以下显示分页信息
......
else 'recordcount=-1
Response.Write "参数错误"
end if


  对于以上代码,只有一点需要说明:同时返回记录集和参数时,若要取得参数,需先将记录集关闭,使用记录集时再将其打开。

瑞星杀毒08套装1年免费用

  7. 返回多个记录集的存储过程

  本文最先介绍的是返回记录集的存储过程。有时候,需要一个存储过程返回多个记录集,在ASP中,如何同时取得这些记录集呢?为了说明这一问题,在userinfo表中增加两个字段:usertel及usermail,并设定只有登录用户可以查看这两项内容。

/*SP7*/
CREATE PROCEDURE dbo.getUserInfo
@userid int,
@checklogin bit
as
set nocount on
begin
if @userid is null or @checklogin is null return
select username
from dbo.[usrinfo]
where userid=@userid
--若为登录用户,取usertel及usermail
if @checklogin=1
select usertel,usermail
from dbo.[userinfo]
where userid=@userid
return
end
go


  以下是ASP代码:

'**调用返回多个记录集的存储过程**
DIM checklg,UserID,UserName,UserTel,UserMail
DIM MyComm,MyRst
UserID = 1
'checklogin()为自定义函数,判断访问者是否登录
checklg = checklogin()
Set MyComm = Server.CreateObject("ADODB.Command")
with MyComm
 .ActiveConnection = MyConStr 'MyConStr是数据库连接字串
 .CommandText = "getUserInfo" '指定存储过程名
 .CommandType = 4 '表明这是一个存储过程
 .Prepared = true '要求将SQL命令先行编译
 .Parameters.append .CreateParameter("@userid",3,1,4,UserID)
 .Parameters.append .CreateParameter("@checklogin",11,1,1,checklg)
 Set MyRst = .Execute
end with
Set MyComm = Nothing

'从第一个记录集中取值
UserName = MyRst(0)
'从第二个记录集中取值
if not MyRst is Nothing then
 Set MyRst = MyRst.NextRecordset()
 UserTel = MyRst(0)
 UserMail = MyRst(1)
end if
Set MyRst = Nothing


  以上代码中,利用Recordset对象的NextRecordset方法,取得了存储过程返回的多个记录集。

  至此,针对ASP调用存储过程的各种情况,本文已做了较为全面的说明。最后说一下在一个ASP程序中,调用多个存储过程的不同方法。

  在一个ASP程序中,调用多个存储过程至少有以下三种方法是可行的:

  1. 创建多个Command对象

DIM MyComm
Set MyComm = Server.CreateObject("ADODB.Command")
'调用存储过程一
......
Set MyComm = Nothing
Set MyComm = Server.CreateObject("ADODB.Command")
'调用存储过程二
......
Set MyComm = Nothing
......


  2. 只创建一个Command对象,结束一次调用时,清除其参数

DIM MyComm
Set MyComm = Server.CreateObject("ADODB.Command")
'调用存储过程一
.....
'清除参数(假设有三个参数)
MyComm.Parameters.delete 2
MyComm.Parameters.delete 1
MyComm.Parameters.delete 0
'调用存储过程二并清除参数
......
Set MyComm = Nothing


  此时要注意:清除参数的顺序与参数声明的顺序相反,原因嘛,我也不知道。

  3. 利用Parameters数据集合的Refresh方法重置Parameter对象

DIM MyComm
Set MyComm = Server.CreateObject("ADODB.Command")
'调用存储过程一
.....
'重置Parameters数据集合中包含的所有Parameter对象
MyComm.Parameters.Refresh
'调用存储过程二
.....
Set MyComm = Nothing


  It is generally believed that objects are created repeating a process less efficient, but tested (testing tool as Microsoft Application Center Test), unexpected results:

  Method 2> Method 3 >> 1 =

  Method speed is not less than 2 1 (up to about 4% higher), the speed is much larger than the two methods method 3 (up to as high as 130%), it is recommended that the parameter is large, the method 1, when few parameters, the method 2.

Published 16 original articles · won praise 1 · views 30000 +

Guess you like

Origin blog.csdn.net/wvtjplh/article/details/3842048