在SQL Server 2008中使用Excelmacros创build临时表(ADODB)

大量的谷歌search后,我已经结束了以下macros,我希望将连接到数据库,删除任何现有的临时表,然后创build一个新的(填充它,并查看结果)。

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来考虑订单号可能有多种types,但我怀疑这是问题发生的地方。

任何帮助是极大的赞赏!

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

我对临时表的理解是,它们只能用于创build它们的连接。 既然如此,试图从另一个连接中删除一个是不明智的。

错误消息没有指出哪一行代码导致它。 既然如此,我build议你testing你的代码零碎。 从创build连接开始。 然后打开并closures它。 然后在连接开放的时候开始做事,但一次只做一件事。