参数集合 (ADO)
言论
Command 对象具有由 参数 对象组成的 Parameters 集合。
对 Command 对象的 Parameters 集合使用 Refresh 方法可检索 Command 对象中指定的存储过程或参数化查询的提供程序参数信息。 某些提供程序不支持存储过程调用或参数化查询;使用此类提供程序时,在 Parameters 集合上调用 Refresh 方法将返回错误。
如果尚未定义自己的 参数 对象,并在调用 Refresh 方法之前访问 Parameters 集合,ADO 将自动调用该方法并填充集合。
如果知道与存储过程关联的参数或要调用的参数化查询的属性,则可以最大程度地减少对提供程序的调用以提高性能。 使用 CreateParameter 方法可以使用适当的属性设置创建 参数 对象,并使用 Append 方法将它们添加到 Parameters 集合。 这使你可以设置和返回参数值,而无需调用提供程序以获取参数信息。 如果要写入不提供参数信息的提供程序,则必须使用此方法手动填充 Parameters 集合才能使用参数。 如有必要,请使用 Delete 方法从 Parameters 集合中删除 参数 对象。
关闭 Recordset 时,Parameters 集合中的对象 超出范围(因此变得不可用)。
使用 Command调用存储过程时,将按如下所示检索存储过程的返回值/输出参数:
调用没有参数的存储过程时,应在调用 Command 对象上的 Execute 方法之前调用 Parameters 集合上的 Refresh 方法。
使用参数调用存储过程并将参数显式追加到具有 Append的 Parameters 集合时,返回值/输出参数应追加到 Parameters 集合中。 必须先将返回值追加到 Parameters 集合中。 使用 追加 按定义顺序将其他参数添加到 Parameters 集合中。 例如,存储过程 SPWithParam 具有两个参数。 第一个参数(InParam)是定义为 adVarChar(20)的输入参数,第二个参数(OutParam)是定义为 adVarChar(20)的输出参数。 可以使用以下代码检索返回值/输出参数。
' Open Connection Conn set ccmd = CreateObject("ADODB.Command") ccmd.Activeconnection= Conn ccmd.CommandText="SPWithParam" ccmd.commandType = 4 'adCmdStoredProc ccmd.parameters.Append ccmd.CreateParameter(, adInteger, adParamReturnValue, , NULL) ' return value ccmd.parameters.Append ccmd.CreateParameter("InParam", adVarChar, adParamInput, 20, "hello world") ' input parameter ccmd.parameters.Append ccmd.CreateParameter("OutParam", adVarChar, adParamOutput, 20, NULL) ' output parameter ccmd.execute() ' Access ccmd.parameters(0) as return value of this stored procedure ' Access ccmd.parameters("OutParam") as the output parameter of this stored procedure.
使用参数调用存储过程并通过对 Parameters 集合调用 Item 方法来配置参数时,可以从 Parameters 集合中检索存储过程的返回值/输出参数。 例如,存储过程 SPWithParam 具有两个参数。 第一个参数(InParam)是定义为 adVarChar(20)的输入参数,第二个参数(OutParam)是定义为 adVarChar(20)的输出参数。 可以使用以下代码检索返回值/输出参数。
' Open Connection Conn set ccmd = CreateObject("ADODB.Command") ccmd.Activeconnection= Conn ccmd.CommandText="SPWithParam" ccmd.commandType = 4 'adCmdStoredProc ccmd.parameters.Item("InParam").value = "hello world" ' input parameter ccmd.execute() ' Access ccmd.parameters(0) as return value of stored procedure ' Access ccmd.parameters(2) or ccmd.parameters("OutParam") as the output parameter.
本节包含以下主题。