I am learning how to use parameters in an excel-driven SQL query (in fact I am still learning SQL in general). Thanks to the nice people that helped me build my query to modify the results as I need, I want to take this a step further and supply a parameter in Excel to filter the results.
Here is my query:
SELECT
fun.FUNCTION_ID
,COALESCE(fun.parent_function, fun2.function_id) as PARENT_FUNCTION
,fun.MODULE_ID
,fun.DESCRIPTION
,fun.FUNCTION_PURPOSE
,fun.PB_OBJECT
,sec.GROUP_ID
,sec.ACCESS_LEVEL
from
MODULE_FUNCTION fun
LEFT JOIN MODULE_FUNCTION fun2
ON fun.function_id = fun2.function_id
AND fun2.function_id IN (SELECT parent_function FROM MODULE_FUNCTION)
LEFT OUTER JOIN FUNCTION_SECURITY sec
ON fun.FUNCTION_ID = sec.FUNCTION_ID
AND sec.GROUP_ID = 'GROUP_NAME'
What I need to do is allow people from a team to run this query in the excel sheet and supply their group name for the “GROUP_NAME” in the second JOIN. Unfortunately I cannot use the syntax WHERE (sec.GROUP_ID = ?) (found here) as I need to pull all results from the MODULE_FUNCTION table and only insert results on the right from the FUNCTION_SECURITY table when there is a match on the supplied group (leaving null when there is no match).
When I try to use AND (sec.GROUP_ID = ?) at the end I get a “Invalid Parameter Number” in Excel. From what I have gathered, the “?” can only be use with WHERE (and works find for me in test queries).
I have tried many things, including declaring a @parameter, but no avail.
I’m tempted to try this technique but I’d like to avoid VB if possible.
I know you said you want to avoid VB, but it isn’t too complicated for what you want to do.
You can have the sheet have a cell for the group name, then a button that calls a macro where you would change the sql query to adjust for the group_id.
Something like:
Where:
is the Group_ID. You can set this to a specific cell in any sheet in your workbook. I would create a button right next to it called “Refresh table” or something like that.
If you already made a table that links to a database, then there is a connection object in Excel. Go to the Data tab, then click “Connections”. A new window will pop up. Find the connection that matches to the SQL query. Click on that connection and click “Properties” then change the connection name to something easy (it’s usually some long name based on the server/table you connect to). Use that for the
section.
Link to create button on worksheet and link to macro:
http://office.microsoft.com/en-us/excel-help/add-a-button-and-assign-a-macro-to-it-in-a-worksheet-HP010236676.aspx