2010-04-22 127 views
2

我發現了一個莫名其妙的錯誤,在VB6運行ADO命令對SQL Server 2005數據庫。VB6 ADO命令到SQL Server

下面是一些代碼來演示該問題:

Sub ADOCommand() 
    Dim Conn As ADODB.Connection 
    Dim Rs As ADODB.Recordset 
    Dim Cmd As ADODB.Command 

    Dim ErrorAlertID As Long 
    Dim ErrorTime As Date 

    Set Conn = New ADODB.Connection 
    Conn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=database;Data Source=server" 
    Conn.CursorLocation = adUseClient 
    Conn.Open 

    Set Rs = New ADODB.Recordset 
    Rs.CursorType = adOpenStatic 
    Rs.LockType = adLockReadOnly 

    Set Cmd = New ADODB.Command 
    With Cmd 
     .Prepared = False 
     .CommandText = "ErrorAlertCollect" 
     .CommandType = adCmdStoredProc 
     .NamedParameters = True 
     .Parameters.Append .CreateParameter("@ErrorAlertID", adInteger, adParamOutput) 
     .Parameters.Append .CreateParameter("@CreateTime", adDate, adParamOutput) 
     Set .ActiveConnection = Conn 
     Rs.Open Cmd 

     ErrorAlertID = .Parameters("@ErrorAlertID").Value 
     ErrorTime = .Parameters("@CreateTime").Value 
    End With 
    Debug.Print Rs.State ''// Shows 0 - Closed 
    Debug.Print Rs.RecordCount ''// Of course this fails since the recordset is closed 
End Sub 

所以這個代碼是工作不是很久以前,但現在它的失敗與錯誤的最後一行:

Run-time error '3704': Operation is not allowed when the object is closed 

爲什麼關閉?我剛打開它,SP返回行。

我跑了蹤跡,這就是ADO庫實際上是提交到服務器:

declare @p1 int 
set @p1=1 
declare @p2 datetime 
set @p2=''2010-04-22 15:31:07:770'' 
exec ErrorAlertCollect @[email protected] output,@[email protected] output 
select @p1, @p2 

運行這是從我的查詢編輯器產量單獨的批處理:

Msg 102, Level 15, State 1, Line 4 
Incorrect syntax near '2010'. 

當然有一個錯誤。看看那裏的雙引號。這可能導致什麼?我嘗試使用adDBDate和adDBTime數據類型的日期參數,他們給了相同的結果。

當我做了參數adParamInputOutput,然後我得到這樣的:

declare @p1 int 
set @p1=default 
declare @p2 datetime 
set @p2=default 
exec ErrorAlertCollect @[email protected] output,@[email protected] output 
select @p1, @p2 

運行,作爲一個單獨的批處理產量:

Msg 156, Level 15, State 1, Line 2 
Incorrect syntax near the keyword 'default'. 
Msg 156, Level 15, State 1, Line 4 
Incorrect syntax near the keyword 'default'. 

什麼鬼? SQL Server不支持這種類型的語法。您只能在實際的SP執行語句中使用DEFAULT關鍵字。

我要指出,從上面的語句刪除多餘的單引號使得SP運行正常。

...哦,我的。我只是想出了它。無論如何,我想這是值得發帖的。

+0

的'「」 datetime'''是在分析器(固定在SP2中,我認爲)只是一個已知的bug – 2010-04-23 11:49:42

+0

感謝。奇怪的是,剖析器會報告與真實情況不同的東西。我將檢查服務器的服務包級別。 – ErikE 2010-04-24 06:12:07

回答

2

答案是存儲過程需要在頂部有SET NOCOUNT ON,因爲ADO在獲得「受影響的行」響應時停止,並且存儲過程在最終選擇之前有更新語句。

我不知道爲什麼跟蹤顯示ADODB的語法,當它自己提交時無法正確運行,但顯然ADODB庫沒有收到其查詢錯誤。整個問題是SET NOCOUNT ON失蹤。

+0

這救了我頭疼,太感謝你了。我有一個大量的SQL命令運行,並提供了NOCOUNT選項! – abbottdev 2016-02-02 17:09:12

+0

如果我的回答對您有用,請使用左側的箭頭進行投票! – ErikE 2016-02-02 17:12:05

2

除了@ErikE提到的內容,如果你的存儲過程包含PRINT語句(即使只是用於調試),ADO也會有一頭牛,產生與你所看到的完全相同的錯誤。