gpt4 book ai didi

sql - 使用 Excel 宏 (ADODB) 在 SQL Server 2008 中创建临时表

转载 作者:行者123 更新时间:2023-12-02 05:41:07 26 4
gpt4 key购买 nike

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

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

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

运行时错误“-2147217887 (80040e21)”:

无法支持请求的属性

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

非常感谢任何帮助!

最佳答案

修改recodset的打开方式,将命令中的select移至recodset打开方法调用。

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)"

关于sql - 使用 Excel 宏 (ADODB) 在 SQL Server 2008 中创建临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14939766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com