I have a scalar function which returns a VARCHAR
of a column name.
I would like to use this result to base a select query upon, so:
SELECT dbo.udf_GetColName('Val1', ColumnFromThisTable, etc) AS myCol
FROM tbl_ThisTable WHERE ...
At the moment, this is correctly listing the actual output of the UDF, the column name, for each value.
What I would like is for the select statement to return the value of the column returned from the function, so:
SET @sql = 'SELECT ' + dbo.udf_GetColName('Val1', ColumnFromThisTable, etc) + ' AS myCol
FROM tbl_ThisTable WHERE ... '
And run EXEC sp_executesql
Is there a better way than the dynamic SQL route? Some way that SQL can query that column as output from the UDF?
EDIT TO ADD
This is where the business need to manage the rules upon which the output is selected hence they need to be in an updateable table. If they're hardcoded into the SELECT
of Table-Valued functions then it is no longer the business that control them.
So yes, the query is very customisable but would be, in this instance "a good thing".
Additionally, there is a finite number of parameters into udf_GetColName
. It receives a source column name, a source column value, which makes a lookup in the rules table. Should the rule find a match of that column to that value, an output column
is selected and returned otherwise a default output column
is used. This is the column that needs to be selected, hence could potentially be quite different to the input or input value.
As said, I'm happy to hear any other ideas and of course if this is silly and another route should be picked!
FINAL EDIT FOR THE DAY BEFORE I GO HOME
I'm looking for a way to select which columns to use from tbl_ThisTable
, based upon other columns values in tbl_ThisTable
.
These rules as to which column to use need to be easily updateable within a table - a major limitation is the interface / front end to the database - we can only return straight datasets so can't use the front end to make this decision / concatenate multiple datasets etc...
If there's a good way to deploy these rules, which can be updated within the database without rewriting code, I'd love to hear them. I'm just testing this at the moment, so design is flexible.