在sql存储过程中找到创建日期和更新日期之间的最新日期

时间:2019-04-01 10:39:29

标签: sql-server stored-procedures

我的表格中有两列作为创建日期和更新日期。我想从中查找最新日期。我想考虑的是最新的日期并从输入值中过滤出来。

我当前的查询是:-

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

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您可以用系统日期减去fromDate和toDate以找到最新日期。通过使用案例,您可以根据最新日期进行过滤。 喜欢:

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

要查找两个日期之间的最新日期,可以使用下面脚本的引用。

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; 

答案 2 :(得分: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

//选择全部运行

答案 3 :(得分:0)

假设更新日期为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