I have two variables, one is called PaidThisMonth
, and the other is called OwedPast
. They are both results of some subqueries in SQL. How can I select the smaller of the two and return it as a value titled PaidForPast
?
The MIN
function works on columns, not variables.
This works for up to 5 dates and handles nulls. Just couldn't get it to work as an Inline function.
SQL Server 2012 and 2014 supports IIF(cont,true,false) function. Thus for minimal selection you can use it like
Use Case:
As Inline table valued UDF
Usage:
ADDENDUM: This is probably best for when addressing only two possible values, if there are more than two, consider Craig's answer using Values clause.
I just had a situation where I had to find the max of 4 complex selects within an update. With this approach you can have as many as you like!
You can also replace the numbers with aditional selects
More complex usage
I'm sure a UDF has better performance.
Use a temp table to insert the range of values, then select the min/max of the temp table from within a stored procedure or UDF. This is a basic construct, so feel free to revise as needed.
For example:
Here is a trick if you want to calculate maximum(field, 0):
returns 0 if
field
is negative, else, returnfield
.