查询date ='2016/01/02'无法正常工作?

时间:2016-04-04 09:42:03

标签: sql-server tsql date datetime sql-server-2014

SQL FIDDLE DEMO HERE

我有这种表结构:

CREATE TABLE Department
(
     [IdDepartment] int, 
     [Name] varchar(23), 
     [IdUser] int, 
     [CreateDate] datetime
);

INSERT INTO Department ([IdDepartment], [Name], [IdUser], [CreateDate])
VALUES
    (1, 'Sales', 3, '2016-01-15 17:00:00.000'),
    (2, 'Finance', null, '2016-01-13 18:00:00.000' ),
    (3, 'Accounting' , 5, '2016-03-21 22:00:00.000'),
    (4, 'IT' ,3, '2016-03-21 17:00:00.000'),
    (5, 'Secretary',null, '2016-03-21 17:00:00.000'),
    (6, 'Sport',3, '2016-02-20 16:00:00.000');

我想运行此查询:

select Name 
from Department 
where CreateDate = '2016-03-21'

结果返回0行。

我认为这是因为表格结构中的日期是日期时间,但我尝试这样做,但对我来说都不适用:

select Name 
from Department 
where CreateDate like '%2016-03-21%'

结果应该是这样的:

Name
-----
Accounting
IT
Secretary

我怎样才能得到这个结果?

我希望我能解释清楚,谢谢

3 个答案:

答案 0 :(得分:4)

您正在将DATETIME值与 2016-03-21 11:00:00进行比较。您必须知道,2016-03-21 包含时间

CAST(YourDate AS DATE)=CAST('2016-03-21' AS DATE) NOT 等于CAST(someCol AS DATE)

您可以像这样比较

BETWEEN

提示:作为一个小例外! - YourDate BETWEEN {d'2016-03-21'} AND {ts'2016-03-21 23:59:59'} 实际上是可以接受的,但值得一提的是,它仍然不是最好的主意:dba.stackexchange.com/a/34052/70663

或者您可以尝试YourDate >= {d'2016-03-21'} AND YourDate < {d'2016-03-22'}

join

或 - 在大多数情况下最喜欢

RouteNo | StopID | VehicleID | RouteID | VehicleNo | TicketCount | Revenue
--------------------------------------------------------------------------
Route_1      0        5           2          DL7S        54         10000

避免因sargability

而对列值进行操作

最好避免使用日期文字...如果必须,可以read this

答案 1 :(得分:1)

使用CAST方法仅比较日期而非时间

SELECT * FROM Department 
WHERE CAST(CreateDate AS DATE) ='2016-03-21'

答案 2 :(得分:0)

完全同意@Shnugo

DECLARE @Department TABLE (
    IdDepartment INT,
    Name VARCHAR(23),
    IdUser INT,
    CreateDate DATETIME
);

INSERT INTO @Department
VALUES
    (1, 'Sales', 3, '2016-01-15 17:00:00'),
    (2, 'Finance', NULL, '2016-01-13 18:00:00'),
    (3, 'Accounting', 5, '2016-03-21 22:00:00'),
    (4, 'IT', 3, '2016-03-21 17:00:00'),
    (5, 'Secretary', NULL, '2016-03-21 17:00:00'),
    (6, 'Sport', 3, '2016-02-20 16:00:00')

DECLARE @Date DATETIME = '20160321' -- ISO format

SELECT Name
FROM @Department
WHERE CreateDate >= @Date
    AND CreateDate < DATEADD(DAY, 1, @Date)