Is there a way to pass a column name as an argument into a function?
I would like to create a function whereby I filter values based upon a column, but I pass this column name into the function (ideally as a string)?
I did try but I declared the column name as a varchar and obviously this wouldnt work!
Short answer: No.
The only way to do that is with Dynamic SQL. It’s not uncommon to make a Stored Procedure that takes field/table names as parameters, and builds a new SQL statement to execute.
Functions, however, can’t execute Dynamic SQL.
This may be an indication of a mis-directed design. If you elaborate on why you need this, we may be able to offer alternative designs where it’s not needed at all.
Or, you may be better suited with a Stored Procedure than a function.
The idea of using a chain of
ORconditions does also meet something like your description. But it normally generates very bad plans. I’ll look up my useful link for an explanation of why and how to deal with it; it’s very in depth, but very good to know.EDIT Here’s the link: Dynamic Search Conditions in T-SQL