3

I have the following select:

SELECT * FROM Table
WHERE Column= datepart(month,'2013-05-07 10:18:00') 
  AND Column= datepart(year,'2013-05-07 10:18:00')

I want it to show me itens where month= 05 and year= 2013. Actually it isn't showing anything (but there is results to be show). Thanks.

4

5 回答 5

11

我会使用 MONTH 和 YEAR 函数

SELECT * FROM Table
WHERE MONTH(yourColumn) = 5  and YEAR(yourColumn) = 2013

http://msdn.microsoft.com/en-us/library/ms186313.aspx

http://msdn.microsoft.com/en-us/library/ms187813.aspx

于 2013-05-10T13:07:33.683 回答
3
SELECT * 
  FROM Table
 WHERE datepart(month, datecolumn) = 5
   AND datepart(year, datecolumn) = 2013
于 2013-05-10T13:04:54.297 回答
2

在列上应用函数通常是个坏主意。它使条件non-sargable

最好间隔测试。

SELECT * 
FROM YourTable
WHERE DateCol >= '20130501' AND
      DateCol < '20130601'

一个可以玩的 SQL Fiddle 证明了我的观点

于 2013-05-10T13:20:21.003 回答
-1

尝试

SELECT * FROM Table WHERE month = DATE_FORMAT('2013-05-07 10:18:00', '%m') AND ...
于 2013-05-10T13:04:51.537 回答
-1

我想你的专栏本身就是一个日期?然后你需要在“=”的两边应用DATEPART

SELECT
        *
    FROM Table
    WHERE
        DATEPART(MONTH, Column)= DATEPART(MONTH,'2013-05-07 10:18:00') 
        AND DATEPART(YEAR, Column) = DATEPART(YEAR,'2013-05-07 10:18:00')
于 2013-05-10T13:14:46.340 回答