Dec 18, 2013

Excel Connect SQL Proc with params


Step 1: Data tab – > From Other Sources -> From SQL Server

.

Step 2: Enter Credentials.

.

Step 3: Choose any small table or view. It doesn’t matter which one because we’ll be changing the connection anyway.

.

Step 4: In the Data Connection Wizard dialog, give your connection a friendly name that you can remember. This is how you’ll point to this connection in VBA. In this case, I’m calling this connection MYSERVER.


.

Step 5: Excel will pop up the Import Data dialog box – Click Properties here (NOT THE OK BUTTON).

.

Step 6: Click on the Definition tab. Here, you’ll want to change Command Type to SQL, and then enter your Stored Procedure name in the Command Text input. As you can see, the SQL statement is simply a call to the Stored Procedure along with the Parameter name (in this case, the procedure is expecting one parameter that accepts a market name).

.

Step 7: Excel warns you about something unimportant – Click Yes (which in this case, means go away).

.

Step 8: Excel will activate the Import Data dialog box again. This time click OK to fire the Stored Procedure and return the results.

.

Step 9: Note the results you get from your original hard-coded command you entered in Step 6. At this point, you know your connection is working.

.

Step 10: Create a mechanism to dynamically select and enter your parameters.
In my case, I need to pass a market name to my Stored Procedure. So I added a simple dropdown where my selection goes to Cell B2. The mechanism you choose to select your parameters is not the important thing here. The important thing is to note where the final selection will be housed. In this example, my market selection will end up in Cell B2.

.

Step 11: The final step is to copy and paste this Macro into a standard module. Notice that all we are dong here is changing the definition fo the CommandText property of the Connection. This basically means that as long as you can point to the correct connection (MYSERVER in this case), you can rebuild the CommandText on the fly. Here, I’m rebuilding the CommandText to point to my chosen cell range (cell B2 – where my market selection is housed).
  1. Sub RefreshQuery()
  2.     With ActiveWorkbook.Connections("MYSERVER").OLEDBConnection
  3.         .CommandText = "EXECUTE dbo.Tng_Market_Feed '" & Range("B2").Value & "'"
  4.     End With
  5.     ActiveWorkbook.Connections("MYSERVER").Refresh
  6.    
  7. End Sub
.

At this point, it’s just a question of firing the Macro each time your parameter selection changes.

http://www.mediafire.com/download/lq7jccmfvqd4yo4/ExcelConnectSQL.rar

http://www.mediafire.com/download/4fowr7d0aa9tf4r/Excel+Connect+SQL+Proc+with+params.doc 

0 comments:

Post a Comment

Nam Le © 2014 - Designed by Templateism.com, Distributed By Templatelib