views:

283

answers:

2

I have two variables, on 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.

+8  A: 

use Case:

   Select Case When @PaidThisMonth < @OwedPast 
               Then @PaidThisMonth Else @OwedPast End PaidForPast

As Inline table valued UDF

CREATE FUNCTION Minimum
(@Param1 Integer, @Param2 Integer)
Returns Table As
Return(Select Case When @Param1 < @Param2 
                   Then @Param1 Else @Param2 End MinValue)

Usage:

Select MinValue as PaidforPast 
From dbo.Minimum(@PaidThisMonth, @OwedPast)
Charles Bretana
You can write function as well for code reusability. But this option would be more efficient
Shantanu Gupta
If you do use UDF, remember to make it an inline table-valued udf to avoid recompilation performance hit...
Charles Bretana
+1  A: 

Use a CASE statement.

Example B should be close to what you're trying to do: http://msdn.microsoft.com/en-us/library/ms181765.aspx

Mike C.