[英]Creating a temp table in SQL Server 2008 using an Excel Macro (ADODB)
經過大量的谷歌搜索,我最終得到了以下宏,我希望連接到數據庫,刪除任何現有的臨時表,然后創建一個新的(填充它,並查看結果)。
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
以考慮訂單號可能有多種類型,但我懷疑這是問題發生的地方。
任何幫助是極大的贊賞!
修改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)"
我對臨時表的理解是它們僅可用於創建它們的連接。 在這種情況下,嘗試從另一個連接中刪除一個是不明智的。
錯誤消息未說明導致它的代碼行。 既然如此,我建議你逐步測試你的代碼。 首先創建連接。 然后打開並關閉它。 然后在連接打開時開始做事,但一次只做一件事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.