0
DROP TABLE IF EXISTS b;

CREATE TABLE b(
    MajDate smalldatetime
);

INSERT INTO b(MajDate) VALUES
(try_convert(smalldatetime,'2016-11-30 11:23:00')),
(try_convert(smalldatetime,'2021-07-07 11:07:00')),
(try_convert(smalldatetime,'2021-07-07 11:07:00'))

select 
b.MajDate,
CASE WHEN b.MajDate BETWEEN '2021-07-01 00:00:00' AND '2021-08-01 00:00:00'
        THEN 'YES'
    ELSE 'NO'
END AS InRange
From b;

What am I doing wrong ?

enter image description here

Desired Output: Column InRange should contain YES for two last rows.

4

2 回答 2

1

它对我有用。

我猜这个问题与您机器上的日期/时间设置有关。

您可能需要检查SET DATEFORMAT ...

设置日期格式 (Transact-SQL)

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE  (ID INT IDENTITY PRIMARY KEY, MajDate smalldatetime);
INSERT INTO @tbl (MajDate) VALUES
('2016-11-30 11:23:00'),
('2021-07-07 11:07:00'),
('2021-07-07 11:07:00');
-- DDL and sample data population, end

SET DATEFORMAT mdy;

SELECT ID, MajDate
    , CASE WHEN MajDate BETWEEN '2021-07-01 00:00:00' AND '2021-08-01 00:00:00'
            THEN 'YES'
        ELSE 'NO'
    END AS InRange
    ,IIF(MajDate BETWEEN '2021-07-01 00:00:00' AND '2021-08-01 00:00:00', 'YES', 'NO')AS result
FROM @tbl;

输出

+----+---------------------+---------+--------+
| ID |       MajDate       | InRange | result |
+----+---------------------+---------+--------+
|  1 | 2016-11-30 11:23:00 | NO      | NO     |
|  2 | 2021-07-07 11:07:00 | YES     | YES    |
|  3 | 2021-07-07 11:07:00 | YES     | YES    |
+----+---------------------+---------+--------+
于 2021-08-31T14:55:55.603 回答
1

尝试指定ISO格式日期,您的区域设置很可能会产生影响。

如果您使用 YYYYMMDD,则没有歧义。以下工作正常:

select 
b.MajDate,
CASE WHEN b.MajDate BETWEEN '20210701 00:00:00' AND '20210801 00:00:00' THEN 'YES' else 'NO'
END AS InRange
From b;
于 2021-08-31T14:58:36.070 回答