用于选择日间隔的SQL语句

时间:2013-05-23 08:18:35

标签: sql-server datediff getdate dateadd

如何动态获取一天之间的范围,例如: BETWEEN 23.05.2012 00:00和23.05.2012 23:59使用MSSQL?我得到了第一部分;

WHERE
AND s.SCHEDULE_START_DATE BETWEEN dateadd(DAY, datediff(DAY, 0, getdate()), 0) AND FILL HERE

2 个答案:

答案 0 :(得分:1)

您必须尝试类似

的内容
s.SCHEDULE_START_DATE >= dateadd(DAY, datediff(DAY, 0, getdate()), 0)
AND s.SCHEDULE_START_DATE < (dateadd(DAY, datediff(DAY, 0, getdate()), 0) + 1)

看一下下面的例子

SQL Fiddle DEMO

答案 1 :(得分:1)

试试这个 -

<强>查询:

DECLARE @Dates TABLE
(
    SCHEDULE_START_DATE DATETIME
)

INSERT INTO @Dates 
VALUES 
    ('20130522'),
    ('20130523'),
    ('20130524'),
    ('20130523 18:00:00'),
    ('20130523 23:59:59')

DECLARE 
      @DateFrom DATETIME = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
    , @DateTo DATETIME = DATEADD(SECOND, 86399, DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0))

SELECT *
FROM @Dates
WHERE SCHEDULE_START_DATE BETWEEN @DateFrom AND @DateTo

<强>输出:

SCHEDULE_START_DATE
-----------------------
2013-05-23 00:00:00.000
2013-05-23 18:00:00.000
2013-05-23 23:59:59.000