Excel – Query parameters in an external connection to sql server

microsoft excelmicrosoft-excel-2010parametersquerysql server

I want to do exactly this: http://dailydoseofexcel.com/archives/2004/12/13/parameters-in-excel-external-data-queries/ but I want to do it in Excel 2010 and also I am querying SQL Server instead of MS Access. Is it possible?

To elaborate on what I want from that link exactly is to have query parameters that reference cells in the worksheet. At present I'm using VBA and a cell change trigger event. Is there a simpler way?


NOTE: Anyone who is using the method in the accepted answer, if you want your spreadsheet to work on a computer that does not have SQL Server installed on it, then you might find this helpful: https://dba.stackexchange.com/a/109221/46815

Best Answer

So I finally figured it out. Here are my steps.

  1. Open a new Excel worksheet (I'm using Excel 2010)
  2. Click on the Data tab on the ribbon
  3. Click the dop down on "From other sources"
  4. Select "From Microsoft Query"
  5. Select your datasource
  6. Pick any table to populate the Columns in your query box - this doesn't matter as we'll override it later - and click Next
  7. Keep clicking next until you get to the finish button, then click finish
  8. Click "Properties..."
  9. Click the "Definition" tab
  10. The connection type should say "Database Query" - if it says that, you can add parameters, if not, it doesn't seem to be able to add parameters
  11. Update your Command Text with the query you want to use to access the SQL database - haven't tried with other databases, but I'm sure it will work on others
  12. In order to create a parameter, simple put a ? in the where clause. e.g. select * from table1 where col1 = ?

There are some issues with adding parameters. They only work in the final where clause. i.e. if you are using subqueries, pivots, cte's etc you can't add parameters in those. Only at the end in the final where clause

  1. Click "Ok" twice - a pop up will appear asking you for the parameter

  2. Fill anything in - we'll change this later

  3. Click anywhere in the results and click "Properties" on the Data tab on the ribbon

  4. Click on the little hand property icon

  5. Click on the Definition Tab

  6. You will now see the "Parameters..." button is clickable. Click it and change the option from prompt for value to Get value from the following cell

If anyone finds a quicker, simpler way - I'm all ears, but this works consistently and with really big complicated queries. So for us, it is the right solution

Related Question