简体   繁体   English

在SQL语句中使用范围值作为参数

[英]Use range values as parameters in SQL Statement

I am connecting to a database via ODBC. 我正在通过ODBC连接到数据库。 I have the SQL Statement written in VBA. 我有用VBA编写的SQL语句。 I have defined three parameters to pass, defined as cell references: 我定义了三个要传递的参数,它们定义为单元格引用:

Dim Param1 As String
Dim Param2 As String
Dim Param3 As String

Param1 = Sheets("SHEET1").Range("P1").Value
Param2 = Sheets("SHEET1").Range("P2").Value`
Param3 = Sheets("SHEET1").Range("P3").Value

The between clause of the Where Statement works fine (Tables are examples) This is the end of the Statement: Where语句的between子句很好用(表为示例)这是该语句的结尾:

(VPXXX.PDXXX Between " + Param1 + " and " + Param2 + "))"

When I try to add an "equal' Statement at the end, I throw an error "General ODBC Error: 当我尝试在末尾添加“等于”语句时,抛出错误“常规ODBC错误:

AND ((VPXXX.PDXXX=" + Param3 + " ))"

Note: The Below end works 注意:下端工作

AND ((VPXXX.PDXXX='LDPDQ'))"

It just hard codes a single vendor 只是硬编码单个供应商

Hope this is enough info ..... First time building a query in SQL. 希望这是足够的信息.....第一次在SQL中构建查询。 thanks in Advance 提前致谢

Assuming your cell value itself isn't enclosed in single-quotation marks, you probably need to change 假设您的单元格值本身未包含在单引号中,则可能需要更改

AND ((VPXXX.PDXXX=" + Param3 + " ))"

to include the quotation marks, ie 包括引号,即

AND ((VPXXX.PDXXX='" + Param3 + "' ))"

As said by @YowE3K, you were missing ' to enclose your values, so your code should be : 正如@ YowE3K所说,您缺少了'来括住您的值,因此您的代码应为:

"VPXXX.PDXXX Between '" + Param1 + "' and '" + Param2 + "')"

and

"AND (VPXXX.PDXXX='" + Param3 + "')"

Btw, if you are using any IN statement in you SQL query, this could come in very handy : 顺便说一句,如果您在SQL查询中使用任何IN语句,这可能会非常方便:

Public Function ConcatSQL(RgToConcat As Range, Optional AllowMultipleS As Boolean = False) As String
Dim CelRg As Range
ConcatSQL = "('"
For Each CelRg In RgToConcat.Cells
    If CelRg.Value <> vbNullString And (InStr(1, ConcatSQL, CelRg.Value) = 0 Or AllowMultipleS) Then
        ConcatSQL = ConcatSQL & CelRg.Value & "', '"
    End If
Next CelRg
ConcatSQL = Left(ConcatSQL, Len(ConcatSQL) - 3) & ")"
End Function

How to use : 如何使用 :

"VPXXX.PDXXX IN " & ConcatSQL(Sheets("SHEET1").Range("P1:P3"))

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

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