Suppose I have a source that I have to query like this:
Select Fields
from TableA A
join TableB B on A.SomeField = B.SomeField
join TableC C on B.SomeField = C.SomeField
Join TableD D on C.SomeField = D.SomeField
Where
CustomMaxDateFunction (A.SomeDateField, B.SomeDateField, C.SomeDateField, D.SomeDateField) > '20130101 23:59:00'
I know I could write the where clause as something like the following but I’d rather not:
Where
A.SomeDateField > '20130101 23:59:00'
OR B.SomeDateField > '20130101 23:59:00'
OR C.SomeDateField > '20130101 23:59:00'
OR D.SomeDateField > '20130101 23:59:00'
Keep in mind that the number of columns to compare would be variable based upon the number of source tables in the join.
Any suggestions as to the least cumbersome way to do this since we’ll have to use the custom function (or stored procedure) repeatedly.
Instead of creating a new function you can just use the build-in MAX aggregate.
or in context of your query:
If that is not clean enough, you can wrap it into a function
And then call it like this:
Stay away from other forms of functions in this query context as they will hurt performance:
http://sqlity.net/en/498/t-sql-tuesday-24-prox-n-funx/
All functions have in common however, that you are fixed to a given number of parameters, so the first option is probably your best bet.
EDIT:
If you really like the idea of a function you could do this:
Now you can call it like this:
You essentially have to pad the unused parameters with NULL. The additional WHERE clause in the function prevents the warning about eliminated NULL values you would get otherwise. As RBarryYoung mentioned in the comments, there is no real optional parameter functionality for functions in SQL Server.