查询超时已过期(运行时错误 - '2147217871'),当我尝试在VBA中执行SQL视图时?

时间:2018-01-08 17:31:38

标签: vba excel-vba excel

以下VBA是我正在进行的工作,我正在接受

  

查询超时过期错误(运行时错误 - '2147217871')

当我尝试执行以下代码时:

Sub ConnectSqlServer2()

    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sConnString As String

    ' Create the connection string.
    sConnString = "Provider=SQLOLEDB;Data Source=adhoc23;" & _
                  "Initial Catalog=database1;" & _
                  "Integrated Security=SSPI;"


    ' Create the Connection and Recordset objects.
    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset

    ' Open the connection and execute.
    conn.Open sConnString
    Set rs = conn.Execute("SELECT * FROM SQLViewName;")

    ' Check we have data.
    If Not rs.EOF Then
        ' Transfer result.
        Sheets(CC).Range("E5:G34").CopyFromRecordset rs
    ' Close the recordset
        rs.Close
    Else
        MsgBox "Error: No records returned.", vbCritical
    End If

    End Sub

请告诉我如何解决超时失误的问题。

1 个答案:

答案 0 :(得分:1)

这取决于您在相关表中有多少记录以及where子句中的内容(如果您在视图中有任何记录)。那可能是你缺少一些索引。

如果缺少索引,请使用:

CREATE NONCLUSTERED INDEX [Ix_name] ON [dbo].[related table] 
(
    [column1] ASC, [column2] ASC....
)

这样你就可以延长超时时间:

...

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim objCmd As New ADODB.Command   

' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=adhoc23;" & _
              "Initial Catalog=database1;" & _
              "Integrated Security=SSPI;"


' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
' Open the connection and execute.
conn.Open sConnString

objCmd.CommandText = "SELECT * FROM SQLViewName"  
objCmd.CommandType = adCmdText 
objCmd.CommandTimeout = 120 'seconds

' Connect to the data source.  
objCmd.ActiveConnection = conn

' Execute once and display...  
Set rs = objCmd.Execute  

' Check we have data.
If Not rs.EOF Then

...