1

I have two column in my table as created date and updated date.I want to find latest date from that.which ever is latest I want to considered that and filter it from input values.

My current query is :-

Select * 
from Emp E 
WHERE (E.USERID=@UserID) and (E.CDATE >= @FromDate AND E.CDATE <= @ToDate) order by qdate desc

4 Answers4

1

You can subtract fromDate and toDate with system date to find the latest date. And by using case you can filter based on the latest date. Like:

SELECT  *
FROM    Emp E
WHERE   ( E.USERID = @UserID )
        AND E.CDATE = CASE WHEN @fromdate - GETDATE() > @toDate - GETDATE()
                           THEN @fromdate
                           ELSE @toDate
                      END;

To find the latest date between two dates, you can use reference of the script below.

DECLARE @fromdate DATETIME, @toDate DATETIME, @date DATETIME
SET @fromdate = '2019-04-05'
SET @toDate = '2019-05-05'

SET @date = CASE WHEN @fromdate - GETDATE() > @toDate - GETDATE() THEN @fromdate
            ELSE @toDate
            END;
SELECT @date; 
Sagar Timalsina
  • 191
  • 3
  • 14
0
declare @cdate smalldatetime,@udate smalldatetime
Select CDATE=max(CDATE ) ,UDATE =max(UDATE ) into #tbldate
from Emp 

set @cdate =(select CDATE from #tbldate)
set @udate =(select udate from #tbldate)

if(@cdate>@udate)
begin 
 Select CDATE as Latest_Date from #tbldate
end
else
begin 
 Select UDATE as Latest_Date from #tbldate
end

//Run this by selecting all

0
SELECT *
FROM Emp E
WHERE (E.USERID = @UserID)
    AND 1 = CASE 
        WHEN E.CDATE >= E.UDATE
            THEN CASE 
                    WHEN (
                            E.CDATE >= @FromDate
                            AND E.CDATE <= @ToDate
                            )
                        THEN 1
                    END
        WHEN E.CDATE < E.UDATE
            THEN CASE 
                    WHEN (
                            E.UDATE >= @FromDate
                            AND E.UDATE <= @ToDate
                            )
                        THEN 1
                    END
        ELSE 0
        END
Mahesh
  • 198
  • 2
  • 16
0

assuming update date is UDATE

select * from Emp E where (E.USERID=@UserID) and (SELECT MAX(V) from (values(E.CDATE), (E.UDATE)) MAX_DATE(V)) BETWEEN @FromDate AND @ToDate

Ken
  • 21
  • 2