VBA ADO Recordset'挂'

时间:2014-04-04 09:51:40

标签: sql sql-server vba ado

我有一个小的VBA脚本在邮件进入时运行,它的想法就是当邮件到达时,使用' To'它访问的电子邮件地址和数据库以及使用电子邮件地址从SQL表中获取策略引用和分支。

我遇到的问题是当objRst.Open strSQL没有运行时 - 脚本就会挂起。

strSQL查询没问题,因为我调试了变量并将输出直接复制并粘贴到SQL Management Studio中,它运行得非常好。

有人能为我解释这个吗?我的语法错了吗?将记录集转换为变量是否出错?

仅供参考我将只返回SQL中的一行,正如您所看到的那样#TOP;'

Sub ChangeSubject(myItem As Outlook.MailItem)
    'Dim myOlapp As Outlook.Application
    'Dim myNameSpace As Outlook.NameSpace
    Dim MyFolder As Outlook.MAPIFolder
    Dim I As Long

    Dim strBranch As String
    Dim strPolRef As String
    Dim strBody As String
    Dim strTo As String

    'Places the Body in a string
    strTo = myItem.To

    'Set SQL Strings
    Set objCnn = New ADODB.Connection
    objCnn.ConnectionString = "Provider=SQLOLEDB;Data Source=xxx-yyy-zzz;Initial Catalog=MyDB;User ID=UserID;Password=MyPassword;"

    Set objRst = Server.CreateObject("ADODB.Recordset")
    'SQL Statement
    strSQL = "SELECT TOP 1 [c].[B@], p.[PolRef@] FROM [dbo].[ic_yyclient] AS c" & _
    " INNER JOIN [dbo].[ic_brpolicy] AS p ON [c].[B@] = [p].[B@] AND [c].[Ref@] = [p].[Ref@]" & _
    " LEFT OUTER JOIN [dbo].[ic_BD_ATS1] AS ats1 ON [p].[B@] = [ats1].[B@] AND [p].[PolRef@] = [ats1].[PolRef@]" & _
    " WHERE [Ptype] IN ('PC','TW') AND (c.[Email] = '" & strTo & "' OR ats1.[Email] = '" & strTo & "' OR ats1.[Parents_email] = '" & strTo & "') AND [Term_code] IS NULL" & _
    " ORDER BY [ats1].[PolRef@] desc"

    Debug.Print strSQL

    objCnn.ConnectionTimeout = 60
    objCnn.Open
    objRst.Open strSQL

    For Each x In objRst.Fields
        strBranch = x.B@
        strPolRef = x.PolRef@
    Next

    Debug.Print strBranch
    Debug.Print strPolRef

    objRst.Close
    objCnn.Close
    Set myItem = Nothing
End Sub

0 个答案:

没有答案