我需要使用VBA进行sql查询。我的查询输入值来自Excel工作表中的列。我需要获取列中存在的所有值,并将其作为输入传递给sqlserver。但我无法得到答案。我将类型不匹配视为错误。任何人都可以帮助我。提前致谢
例如在J列中包含J1 = 25,j2 = 26,....等等
stSQL = "SELECT * FROM prod..status where state in"
stSQL = stSQL & wsSheet.Range("J:J").Value
我的完整代码位于
之下Sub Add_Results_Of_ADO_Recordset()
'This was set up using Microsoft ActiveX Data Components version 2.8
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim stSQL As Variant
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnStart As Range
Const stADO As String = "Provider=SQLOLEDB.1;Integrated Security=SSPI;" & _
"Persist Security Info=False;" & _
"Initial Catalog=prod;" & _
"Data Source=777777777V009D\YTR_MAIN4_T"
'where BI is SQL Database & AURDWDEV01 is SQL Server
Set wbBook = ActiveWorkbook
Set wsSheet = wbBook.Worksheets("sheet1")
With wsSheet
Set rnStart = .Range("A2")
End With
' My SQL Query
stSQL = "SELECT * FROM prod..status where state in"
stSQL = stSQL + wsSheet.Range("J:J").Value
Set cnt = New ADODB.Connection
With cnt
.CursorLocation = adUseClient
.Open stADO
.CommandTimeout = 0
Set rst = .Execute(stSQL)
End With
'Here we add the Recordset to the sheet from A1
rnStart.CopyFromRecordset rst
'Cleaning up.
rst.Close
cnt.Close
Set rst = Nothing
Set cnt = Nothing
End Sub
答案 0 :(得分:0)
stSQL变量中的“in”后面没有空格。因此,如果您的单元格包含值“TEST”,则stSQL将为
SELECT * FROM prod..status where state inTEST
答案 1 :(得分:0)
更改为
stSQL = stSQL + " ('" + Replace(wsSheet.range("J:J").Value, "'", "") + ")"
但是sql IN语句通常像这样使用
state IN (25,26,28)
但是如果你只使用一个整数值,你可能想要这样。
stSQL = "SELECT * FROM prod..status where state = "
stSQL = Val(wsSheet.range("J:J").Value)
使用in语句有一件事很危险。 如果你的声明的部分内容非常长,那么它会变得很慢,然后在语句崩溃时会更大。
针对这种情况的解决方案是使用in值创建临时表,并根据临时表执行其中(临时表)或内部联接
答案 2 :(得分:0)
我用loop和mid命令将列中的值转换为单个变量。下面是我用来执行我需要的功能的代码
' Getting the last row
With wsSheet
lastrow1 = .Range("J" & .Rows.Count).End(xlUp).Row
End With
' Appending the values to a single variable
For i = 1 To lastrow
s1 = s1 & "'" & Val(wsSheet.Cells(i, 10)) & "'" & ","
Next
' Variable which could be used in IN command
If lastrow > 0 Then
s1 = Mid(s1, 1, Len(s1) - 1)
s1 = "(" & s1 & ")"
Else
Exit Sub
End If