亚多布.记录集不处理 SQL 变量



我正在尝试使用VBA代码从SQL Server数据库中提取数据。我在保存具有更复杂的 SQL 查询的记录集对象时遇到问题。一旦我使用了一个简单的 SQLSELECT语句,一切正常,但是当声明变量(例如(时,我在带有.Cells(2, 1).CopyFromRecordset record_set的行上收到运行时错误,因为record_set为空。我将 SQL 语句保存在.txt文件中,因为原始版本大约有 100 行长。下面只是一个例子。

这是我的VBA代码:

Option Explicit
Sub db_sql()
Dim conn As New ADODB.Connection
Dim record_set As New ADODB.Recordset
Dim sConnect As String
Dim sqlQry
sqlQry = read_sql("C:UsersDesktoptest_sql.txt")
sConnect = "Driver={SQL Server};Server=FOO; Database=BAR;Trusted_Connection=yes;"
conn.Open sConnect
Set record_set = New ADODB.Recordset
record_set.Open sqlQry, conn
With Worksheets("SQL_data")
.Cells.ClearContents
.Cells(2, 1).CopyFromRecordset record_set
End With
record_set.Close
conn.Close
Set record_set = Nothing
End Sub

Function read_sql(txt_path As String) As String
Dim text As String, text_line As String
Open txt_path For Input As #1
Do While Not EOF(1)
Line Input #1, text_line
text = text & text_line & vbLf
Loop
Close #1
read_sql = text
End Function

以下是"test_sql.txt"中缩短的SQL 语句:

DECLARE @date_from DATETIME
DECLARE @date_to DATETIME
SET @date_from = '2020-02-11 06:00'
SET @date_to = '2020-02-12 18:00'
SELECT TOP (1000) * FROM [FOO_DATABASE].[dbo].[BAR_TABLE] where DATESTAMP between @date_from and @date_to

任何想法如何修复我的代码?

Put

SET NOCOUNT ON

在 SQL 批处理的顶部。

最新更新