简体   繁体   English

如何在ASP中使用可选参数将参数名称传递到存储过程中

[英]How to pass a parameter name into a stored procedure with an optional param in asp

I am using a classic ASP application and the ADODB.Recordset and SQL Server. 我正在使用经典的ASP应用程序以及ADODB.Recordset和SQL Server。

When I am using a stored procedure: 当我使用存储过程时:

command.Parameters.Append command.CreateParameter name:="name", value:="value"

size and direction too 大小和方向

the stored procedure I am using has an optional parameter. 我正在使用的存储过程具有可选参数。

So I only pass the param I need (the 3th and the 8th param only in this case) 因此,我仅传递所需的参数(在这种情况下,仅第3和第8个参数)

I am getting an error, when I look with SQL Server profiler, I can see that the param has been passed without the param name (only the value) 我收到错误消息,当我使用SQL Server Profiler进行查看时,可以看到参数已传递而没有参数名称(仅值)

And that the cause to the error 那就是错误的原因

What am I doing wrong? 我究竟做错了什么?

Thanks 谢谢

You need to set the command's property NamedParameters = True and prepend @ character to each parameter's name. 您需要设置命令的属性NamedParameters = True并在每个参数的名称前添加@字符。 Taken from the official documentation : 取自官方文件

When this property is true, ADO passes the value of the Name property of each parameter in the Parameter collection for the Command Object. 当此属性为true时,ADO将为Command Object传递Parameter集合中每个参数的Name属性的值。 The provider uses a parameter name to match parameters in the CommandText or CommandStream properties. 提供程序使用参数名称来匹配CommandText或CommandStream属性中的参数。 If this property is false (the default), parameter names are ignored and the provider uses the order of parameters to match values to parameters in the CommandText or CommandStream properties 如果此属性为false(默认值),则参数名称将被忽略,并且提供程序使用参数顺序将值与CommandText或CommandStream属性中的参数进行匹配

This problem occurs because of the way you are building the parameters, you must declare all parameters and append them to the parameters collection regardless of whether they will be executed. 发生此问题的原因是您构建参数的方式,无论是否执行这些参数,都必须声明所有参数并将它们附加到参数集合中。

With command
    'Declare all the parameters required or not in the order they 
    'should be applied and append them to the Parameters Collection.
    .Parameters.Append(.CreateParameter("name1", adVarWChar, adParamInput, 50))
    .Parameters.Append(.CreateParameter("name2", adVarWChar, adParamInput, 50))
    .Parameters.Append(.CreateParameter("name3", adVarWChar, adParamInput, 50))
    .Parameters.Append(.CreateParameter("name4", adVarWChar, adParamInput, 50))

    'Only define values for parameters you wish to pass.
    'In this case only "name2" and "name4" parameters are passed.
    .Parameters("name2").Value = "My Name 2 Value"
    .Parameters("name4").Value = "My Name 4 Value"
End With

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM