6

经过大量的谷歌搜索,我最终得到了以下宏,我希望它可以连接到数据库,删除任何现有的临时表,然后创建一个新表(填充它并查看结果)。

Dim adoCn As ADODB.Connection
Dim adoRs As ADODB.Recordset
Dim adoCm As ADODB.Command
Dim strSQL As String

Set adoCn = New ADODB.Connection
With adoCn
    .ConnectionString = "Provider=SQLOLEDB;" & _
                        "Initial_Catalog=XXX;" & _
                        "Integrated Security=SSPI;" & _
                        "Persist Security Info=True;" & _
                        "Data Source=XXX;" & _
                        "Extended Properties='IMEX=1'"
    .CursorLocation = adUseServer
    .Open
End With

Set adoCm = New ADODB.Command

With adoCm
    Set .ActiveConnection = adoCn
    .CommandType = adCmdText
    .CommandText = "IF OBJECT_ID('tempdb..#AgedProducts') IS NOT NULL DROP TABLE #AgedProducts"
    .Execute
    .CommandText = "CREATE TABLE #AgedProducts " & _
                   "(Source_Order_Number VARCHAR(255)) " & _
                   "INSERT INTO #AgedProducts VALUES ('AB-123-456') " & _
                   "SELECT * FROM #AgedProducts (NOLOCK) "
    .Execute
End With

Set adoRs = New ADODB.Recordset
With adoRs
    Set .ActiveConnection = adoCn
    .LockType = adLockBatchOptimistic
    .CursorLocation = adUseServer
    .CursorType = adOpenForwardOnly
    .Open "SET NOCOUNT ON"
End With
adoRs.Open adoCm

MsgBox "Recordset returned...", vbOKOnly

While Not adoRs.EOF
    Debug.Print adoRs.Fields(0).Value
    adoRs.MoveNext
Wend

adoCn.Close

Set adoCn = Nothing
Set adoRs = Nothing

当我运行查询时,我收到以下错误消息:

Run-time error '-2147217887 (80040e21)':

The requested properties cannot be supported

NOCOUNT行来自http://support.microsoft.com/kb/235340(与上述大部分代码一样)。我添加IMEX=1了考虑到订单号可能有多种类型,但我怀疑这就是问题所在。

任何帮助是极大的赞赏!

4

2 回答 2

6

修改recodset的打开方式,将select从命令移到recodset open方法调用。

With adoCm
    Set .ActiveConnection = adoCn
    .CommandType = adCmdText
    .CommandText = "IF OBJECT_ID('tempdb..#AgedProducts') IS NOT NULL DROP TABLE #AgedProducts"
    .Execute
    .CommandText = "CREATE TABLE #AgedProducts " & _
                   "(Source_Order_Number VARCHAR(255)) " & _
                   "INSERT INTO #AgedProducts VALUES ('AB-123-456') "
    .Execute
End With

Set adoRs = New ADODB.Recordset
With adoRs
    Set .ActiveConnection = adoCn
    .LockType = adLockBatchOptimistic
    .CursorLocation = adUseServer
    .CursorType = adOpenForwardOnly

End With
adoRs.Open "SELECT * FROM #AgedProducts (NOLOCK)"
于 2013-02-18T16:17:35.940 回答
0

我对临时表的理解是它们仅对创建它们的连接可用。在这种情况下,试图从另一个连接中删除一个是不明智的。

错误消息没有说明是哪一行代码导致了它。既然如此,我建议您逐个测试您的代码。首先创建连接。然后打开并关闭它。然后在连接打开时开始做事,但一次做一件事。

于 2013-02-18T15:40:14.880 回答