Excel VBA调用SQL存储过程返回虚假连接错误

时间:2016-12-14 16:56:37

标签: sql-server excel-vba stored-procedures oledbconnection vba

我正在编写一个脚本来循环遍历Excel工作表,将参数传递给SQL Server过程,该过程需要三个参数并根据参数生成记录。当我进行调用时,它实际上确实传递了参数,执行过程并写入记录,但随后我收到运行时错误" 1004查询未运行..."

我发现了要更改后台查询= False的注释 - 请检查。设置NoCount On - 检查......仍然出现错误。

SQL Server过程确实包含一个ReturnValue parm(1/0),我没有通过它,因为它表示" Too Many Parameters"当我试着这样做的时候。这可能是问题吗?不确定如何收到返回值。

这是我的VBA代码:

$builder->add('tags', TextType::class);

$builder->get('tags')
        ->addModelTransformer(new CallbackTransformer(
                function ($tagsAsArray) {
                    // transform the array to a string
                    return implode(', ', $tagsAsArray);
                },
                function ($tagsAsString) {
                    // transform the string back to an array
                    return explode(', ', $tagsAsString);
                }
            ))
        ;

以下是在SQL Server中手动调用过程并输入Parms:

时生成的脚本
Sub CallProc()
    Dim ws As Worksheet
    Worksheets("AllTags").Activate

    Dim Parm1 As String
    Dim Parm2 As String
    Dim Parm3 As Integer
    Dim RowIndex As Long
    Dim ReturnValue As Integer

    RowIndex = 2

   Do While Sheets("AllTags").Cells(RowIndex, 2).Value <> ""

   If Sheets("AllTags").Cells(RowIndex, 3).Value > 0 Then
   ReturnValue = 0
   Parm1 = Sheets("AllTags").Cells(RowIndex, 1).Value
   Parm2 = Sheets("AllTags").Cells(RowIndex, 2).Value
   Parm3 = Sheets("AllTags").Cells(RowIndex, 3).Value

   With ActiveWorkbook.Connections("TagUpload").OLEDBConnection

   ' SET NOCOUNT ON;  ** IT DOESN'T LIKE THIS 

    .BackgroundQuery = False
    .CommandText = "EXECUTE DCSTransfer.dbo.InsertTags '" & Parm1 & "', '" &  
        Parm2 & "', " & Parm3
    .CommandType = xlCmdSql
    .Connection = Array( _
    "OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security  
     Info=True;Initial Catalog=DCSTransfer;Data Source=bdata03;Use Proc" _
    , _
    "edure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation 
      ID=B-MIS-NWILSON1;Use Encryption for Data=False;Tag with co" _
    , "lumn collation when possible=False;")


    .RefreshOnFileOpen = False
    .SavePassword = False
    .SourceConnectionFile = ""
    .SourceDataFile = ""
    .ServerCredentialsMethod = xlCredentialsMethodIntegrated

     ActiveWorkbook.Connections("TagUpload").Refresh
    .BackgroundQuery = False

     On Error Resume Next  ' **** NEVER GETS THIS FAR ***

     End With

     End If

     RowIndex = RowIndex + 1
     Loop

     End
 End Sub

还有其他建议吗?

1 个答案:

答案 0 :(得分:0)

想出来......经过两天+整天的痛苦之后!

更改了CommandText以匹配存储过程:

    .CommandText = "Declare @return_Value int EXEC @return_Value = DCSTransfer.dbo.InsertTags '" & Parm1 & "', '" & Parm2 & "', " & Parm3 & "SELECT 'Return Value' = @return_value"