ASP Classic的正确ASP字符串连接

时间:2015-05-20 17:53:04

标签: 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

基于其他资源,似乎& symbol是连接变量的正确用法,但错误另有说明:

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

思考?感谢您的帮助和帮助。

1 个答案:

答案 0 :(得分:3)

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

日期可能需要撇号,如下所示:

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等)不太确定。你所谓的变量似乎并不重要,但它们确实需要某种名称才能使它起作用。