Calling a Stored Procedure from Excel with multiple parameters

后端 未结 4 778
生来不讨喜
生来不讨喜 2021-01-14 04:54

I have set up a connection to my SQL server to the database where the stored procedure is located. The Stored Procedure works fine in SQLServer. The Stored Procedure runs

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-14 05:24

    When you execute a stored procedure, the statement generally looks like:

    EXECUTE myProc('param1', 'param2')
    

    The way your command will expand will come out like:

    EXECUTE myProc 'param1param2`
    

    Which is nonsense. Try instead:

    With ActiveWorkbook.Connections("CARLA-PC-Billing-SP").OLEDBConnection.CommandText = "EXECUTE dbo.GetBillingHeatMap ('" & Range("A9").Value & "','" & Range("B9").Value & "');"
    

    You may still run into issues with the date formatting, so you can handle that in VBA too:

    With ActiveWorkbook.Connections("CARLA-PC-Billing-SP").OLEDBConnection.CommandText = "EXECUTE dbo.GetBillingHeatMap ('" & FORMAT(Range("A9").Value, "m/d/yyyy") & "','" & FORMAT(Range("B9").Value, "m/d/yyyy") & "');"
    

    Lastly, I find it good practice to send dynamically generated sql to a variable, and print it to the debug/immediate window before executing so I can catch stuff like that.

    sqlStatement = "EXECUTE dbo.GetBillingHeatMap ('" & FORMAT(Range("A9").Value, "m/d/yyyy") & "','" & FORMAT(Range("B9").Value, "m/d/yyyy") & "');"
    debug.print sqlStatement
    With ActiveWorkbook.Connections("CARLA-PC-Billing-SP").OLEDBConnection.CommandText = sqlStatement
    

    And now you'll have your statement in your immediate window, which you can copy and paste into a SQL client to execute independently of your code.

提交回复
热议问题