简体   繁体   English

ADODB.Recordset 不处理 SQL 变量

[英]ADODB.Recordset doesn't handle SQL variables

I'm trying to use a VBA code to pull out data from a SQL Server database.我正在尝试使用 VBA 代码从 SQL 服务器数据库中提取数据。 I'm having an issue with holding a Recordset object with a more complicated SQL query.我在保存带有更复杂的 SQL 查询的 Recordset object 时遇到问题。 Once I use a simple SQL SELECT statement everything works fine, but when declare variables (for example) I get a Run-time error on the line with .Cells(2, 1).CopyFromRecordset record_set because the record_set is empty.一旦我使用了一个简单的 SQL SELECT语句,一切正常,但是当声明变量(例如)时,我在.Cells(2, 1).CopyFromRecordset record_set行出现运行时错误,因为 record_set 为空。 I keep the SQL statement in an .txt file, because the original version is about 100 lines long.我将 SQL 语句保留在.txt文件中,因为原始版本大约有 100 行长。 Below just an example.下面只是一个例子。

Here is my VBA code:这是我的 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:\Users\Desktop\test_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

Here is the shortened SQL statement in the "test_sql.txt":这是“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

Any ideas how to fix my code?任何想法如何修复我的代码?

Put

SET NOCOUNT ON

at the top of your SQL batch.在您的 SQL 批次的顶部。

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

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