ASP 经典 ASP 的正确字符串连接

Proper ASP String Concatenation for ASP Classic

我在为 SQL 命令获取格式正确的字符串时遇到问题 我设置了三个变量:

Dim pastMonth, currentMonth, futureMonth
currentMonth = Month(Date())
pastMonth = currentMonth-1
futureMonth = currentMonth+1

我尝试设置的字符串是:

strSQL="SELECT * FROM Project WHERE P_MONTH BETWEEN " & pastMonth &" AND " & futureMonth

根据其他资源,& 符号似乎是连接变量的正确用法,但错误指出:

[Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression. 

想法?感谢您的帮助和帮助。

是的,使用&符号是连接字符串的方法。

可能是日期需要撇号,像这样:

strSQL="SELECT * FROM Project WHERE P_MONTH BETWEEN '" & pastMonth &"' AND '" & futureMonth & "'"

但我强烈建议您改变方法并使用参数化查询来执行此操作。

我在经典 asp 中使用如下代码:

public function select_rst(sql, parameterArray)
    dim cnx, cmd, i
    Set cnx=CreateObject("ADODB.Connection")
    cnx.Open wfDataConnection       
    Set cmd = CreateObject("ADODB.Command")
    With cmd    
        .CommandText = sql
        .CommandType = adCmdText
        .ActiveConnection = cnx 
        if isArray(parameterArray) then             
            for each i in parameterArray
                .Parameters.Append .CreateParameter(i(0), i(1), i(2), i(3), i(4))
            next
        end if
    end with
    Set select_rst = CreateObject("ADODB.Recordset")
    With select_rst
        .CursorLocation = adUseClient
        .Open cmd
        Set .ActiveConnection = Nothing
    End With            
    Set cmd = Nothing
    cnx.close
    set cnx=nothing     
end function

这样称呼它:

dim sql, parameterArray
sql = "SELECT * FROM Project WHERE P_MONTH BETWEEN ? AND ?"
parameterArray = Array(_
                     Array("@p1", adInteger, adParamInput, , pastMonth)_
                    , Array("@p2", adInteger, adParamInput, , futureMonth)_
                 )

set rst = select_rst(sql, parameterArray)

    '....do stuff with rst...

set rst = nothing

我不太确定创建参数时的变量名(@p1、@p2 等)。变量的名称似乎无关紧要,但它们确实需要某种名称才能正常工作。