Share via

Return largest date

David Chase 681 Reputation points
2021-07-15T17:52:33.727+00:00

I have SQL 2016 stored procedure that I want to pass the highest of 3 date fields to a UDF (dbo.GetBusinessHoursOut). The current code is shown below. Besides InsuranceApproved and ArrivalDate I want to compare ScheduledInDate so that I pass the most recent date value to the UDF.

SELECT CASE WHEN R.JobSize = 'S'   
		AND @Stage = 1   
		THEN dbo.GetBusinessHoursOut (CASE WHEN R.InsuranceApproved > R.ArrivalDate THEN R.InsuranceApproved   
						   ELSE R.ArrivalDate   
						   END, 1)  
FROM dbo.RepairOrder R  
WHERE R.ScheduledInDate > '2021-01-01'  


  
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

Answer accepted by question author

Viorel 127K Reputation points
2021-07-15T19:25:45.167+00:00

There are several methods: https://www.bing.com/search?q=t-sql+max+of+three+values. For example:

CASE WHEN InsuranceApproved >= ArrivalDate AND InsuranceApproved >= ScheduledInDate THEN InsuranceApproved 
     WHEN ArrivalDate >= ScheduledInDate THEN ArrivalDate
     ELSE ScheduledInDate END

(It assumes that the values are not null).

You will also find this:

(SELECT MAX(d) FROM (VALUES (InsuranceApproved), (ArrivalDate), (ScheduledInDate)) D(d))

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 134.7K Reputation points MVP Volunteer Moderator
    2021-07-15T22:31:23.443+00:00

    As a teaser, on Azure SQL DB, you can say:

    greatest(InsuranceApproved, ArrivalDate, ScheduledInDate)
    

    plain and simple.

    But this is not yet available in the box product.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.