使用VBA从SQL Server查询VIEW

时间:2018-04-23 21:18:12

标签: sql sql-server vba excel-vba excel

我正在尝试创建一个VBA脚本,该脚本将从SELECT * FROM view_name属性的视图(RecordSet.Source)中提取结果,但在尝试时,我的 CloseConnection 错误处理程序一直被抓住。我可以使用像SELECT * FROM tbl_name这样的简单查询从表中获取结果,没有任何问题。

以下是我正在使用的代码。注意:我的Const变量删除了提供者和数据库信息。

我想它真的可以归结为甚至可以从一张桌子上获得一个View的结果吗?

Option Explicit

Const ConStrMSSQL As String = _
"Provider=provider_name;Database=database_name;Trusted_Connection=yes;"

Sub test()

    Dim formConnect As ADODB.connection
    Dim formData As ADODB.recordSet
    Dim formField As ADODB.Field

    Set formConnect = New ADODB.connection
    Set formData = New ADODB.recordSet

    formConnect.ConnectionString = ConStrMSSQL

    formConnect.Open

    On Error GoTo CloseConnection

    With formData
        .ActiveConnection = formConnect
        .Source = "SELECT * FROM v_data_extract_658"
        .LockType = adLockReadOnly
        .CursorType = adOpenForwardOnly
        .Open
    End With

    On Error GoTo CloseRecordset


    Sheets("test").Range("A1").Select

    For Each formField In formData.Fields
        ActiveCell.Value = formField.Name
        ActiveCell.Offset(0, 1).Select
    Next formField

    Sheets("test").Range("A2").CopyFromRecordset formData

    On Error GoTo 0

    CloseRecordset:
        formData.Close

    CloseConnection:
        formConnect.Close


End Sub

这是错误消息:

  

运行时错误2147467259(80004005):从SQL Server收到的未知令牌

2 个答案:

答案 0 :(得分:0)

我认为这里最大的问题是你还没有定义一个命令对象。

我有点把它放在一起"写意"并且肯定没有测试它,但它应该让你到达你需要去的地方。

Sub test()

On Error GoTo ErrorHandle:

    Dim formConnect As ADODB.Connection
    Set formConnect = New ADODB.Connection

    formConnect.ConnectionString = ConStrMSSQL

    Dim cmd   As ADODB.Command
    Set cmd = New ADODB.Command

    formConnect.Open

    With cmd
        .ActiveConnection = formConnect
        .CommandType = adCmdText
        .CommandText = "SELECT * FROM v_data_extract_658"
        .CommandTimeout = 30
    End With

    Dim formData   As ADODB.Recordset
    Set formData = New ADODB.Recordset

    formData.Open cmd, , adOpenStatic, adLockReadOnly

    Sheets("test").Range("A1").Select

    Dim formField As ADODB.Field
    For Each formField In formData.Fields
        ActiveCell.value = formField.Name
        ActiveCell.Offset(0, 1).Select
    Next formField

    Range("A2").CopyFromRecordset formData

    On Error GoTo 0

Cleanup:
    If Not formData Is Nothing Then
        If formData.State <> adStateClosed Then formData.Close
        Set formData = Nothing
    End If

    If Not formConnect Is Nothing Then
        If formConnect.State <> adStateClosed Then formConnect.Close
        Set formConnect = Nothing
    End If

    Set cmd = Nothing

    Exit Sub

ErrorHandle:
    MsgBox Err.Description

    'Do whatever else is needed to respond to errors.

    Resume Cleanup

End Sub

答案 1 :(得分:0)

使用Excel&amp;从SLQ服务器获取dta的VBA非常简单(并非总是如此,但最近)。

Sub ADOExcelSQLServer()
     ' Carl SQL Server Connection
     '
     ' FOR THIS CODE TO WORK
     ' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library
     '

    Dim Cn As ADODB.Connection
    Dim Server_Name As String
    Dim Database_Name As String
    Dim User_ID As String
    Dim Password As String
    Dim SQLStr As String
    Dim rs As ADODB.Recordset
    Set rs = New ADODB.Recordset

    Server_Name = "EXCEL-PC\SQLEXPRESS" ' Enter your server name here
    Database_Name = "NORTHWND" ' Enter your database name here
    User_ID = "" ' enter your user ID here
    Password = "" ' Enter your password here
    SQLStr = "SELECT * FROM [Customers]" ' Enter your SQL here

    Set Cn = New ADODB.Connection
    Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
    ";Uid=" & User_ID & ";Pwd=" & Password & ";"

    rs.Open SQLStr, Cn, adOpenStatic
     ' Dump to spreadsheet
    For iCols = 0 To rs.Fields.Count - 1
        Worksheets("Sheet1").Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
    Next
    With Worksheets("sheet1").Range("a2:z500") ' Enter your sheet name and range here
        '.ClearContents
        .CopyFromRecordset rs
    End With
     '            Tidy up
    rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing
End Sub

顺便说一下,您也可以试试这个(请根据您的具体设置/配置进行更改)......

Sub Working2()

Dim con As Connection
Dim rst As Recordset
Dim strConn As String

Set con = New Connection
strConn = "EXCEL-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True"

con.Open strConn

'Put a country name in Cell E1
Set rst = con.Execute("Exec dbo.MyOrders '" & ActiveSheet.Range("E1").Text & "'" & ActiveSheet.Range("E2").Text & "'")

'The total count of records is returned to Cell A5
ActiveSheet.Range("A5").CopyFromRecordset rst

rst.Close
con.Close

End Sub

请参阅以下链接了解详情。

https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#Excel%20Data%20Export%20to%20SQL%20Server%20Test%20Code