SQL - 大于日期的查询不起作用

时间:2016-08-02 12:14:08

标签: sql sql-server

我正在使用下面的SQL查询,我只想获得“Last Update Date”列大于或等于01/01/2016的记录。基本上只有2016年的记录。当我使用下面的查询时,我没有得到任何错误,但我仍然得到的每个日期不仅仅是2016年。我的语法是否有问题?

SELECT
  NPI,
  [Entity Type Code],
  [Replacement NPI],
  [Employer Identification Number (EIN)],
  [Provider Organization Name (Legal Business Name)],
  [Provider Last Name (Legal Name)],
  [Provider First Name],
  [Provider Middle Name],
  [Provider Name Prefix Text],
  [Provider Name Suffix Text],
  [Provider Credential Text],
  [Provider Other Organization Name],
  [Provider Other Organization Name Type Code],
  [Provider Other Last Name],
  [Provider Other First Name],
  [Provider Other Middle Name],
  [Provider Other Name Prefix Text],
  [Provider Other Name Suffix Text],
  [Provider Other Credential Text],
  [Provider Other Last Name Type Code],
  [Provider First Line Business Mailing Address],
  [Provider Second Line Business Mailing Address],
  [Provider Business Mailing Address City Name],
  [Provider Business Mailing Address State Name],
  [Provider Business Mailing Address Postal Code],
  [Provider Business Mailing Address Country Code (If outside U S )],
  [Provider Business Mailing Address Telephone Number],
  [Provider Business Mailing Address Fax Number],
  [Provider First Line Business Practice Location Address],
  [Provider Second Line Business Practice Location Address],
  [Provider Business Practice Location Address City Name],
  [Provider Business Practice Location Address State Name],
  [Provider Business Practice Location Address Postal Code],
  [Provider Business Practice Location Address Country Code (If outside U S )],
  [Provider Business Practice Location Address Telephone Number],
  [Provider Business Practice Location Address Fax Number],
  [Provider Enumeration Date],
  [Last Update Date]
FROM Data
WHERE ([Healthcare Provider Taxonomy Code_1] IN ('122300000X', '1223G0001X'))
AND ([Last Update Date] >= '01/01/2016')

3 个答案:

答案 0 :(得分:1)

使用以下代码([Last Update Date] >= '01/01/2016')

YEAR( [Last Update Date]) = 2016

获取2016年更新的所有记录

答案 1 :(得分:1)

在条件中使用Datetime:

and CONVERT(datetime, [Last Update Date], 121) >= CONVERT(datetime,'01/01/2016',121)

答案 2 :(得分:1)

使用此:

WHERE CONVERT(datetime, [Last Update Date], 101) >= '2016-01-01'

请注意,您需要的格式掩码为101,与mm/dd/yyyy格式的数据相对应(请参阅documentation)。这假设您以这种格式存储日期,并在比较时以原始WHERE子句中使用的格式说明。

另请注意,您不需要在上述表达式的比较的RHS上使用CONVERT,因为SQL Server应该能够处理日期文字,假设它是标准格式。 / p>