I am a bit puzzled about the best way to construct a stored procedure that returns a SELECT-statement based on table row values in another table.
The problem might be best described as this:
Table Name: reportValues
--------------------------------------------
ID name date region
--------------------------------------------
1 Stefan 2010-01-01 UK
2 David 2010-01-05 SE
3 Anna 2010-01-12 NO
4 Marie 2010-01-15 NO
Table Name: reportParameters
-------------------------------
ID column queryValue
-------------------------------
1 ID
2 name
3 date
4 region
Based on what the user enters in the queryValue column in the reportParameters table, I want to construct a stored procedure what executes a SELECT-statement such as this:
SELECT * FROM reportValues WHERE region = 'NO'
If the user had entered the following values:
Table Name: reportParameters
-------------------------------
ID column queryValue
-------------------------------
1 ID
2 name
3 date
4 region NO
But it might as well be:
SELECT * FROM reportValues WHERE region = 'NO' AND name = 'Anna'
If the user had entered:
Table Name: reportParameters
-------------------------------
ID column queryValue
-------------------------------
1 ID
2 name Anna
3 date
4 region NO
My initial thought of doing it was to make a loop that constructs the SELECT-statement into a string variable and executes it. But it got to be a more elegant solution?
I’m not sure there is, if the queries have a small, known, set of fields, then you could list them all in the where accompanied a selector:
There is no short-circuit evaluation, but it might still have the desired effect. Otherwise it is down to dynamic SQL and
EXEC().