Question

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.

Was it helpful?

Solution

I would use the MONTH and YEAR functions

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

OTHER TIPS

SELECT * 
  FROM Table
 WHERE datepart(month, datecolumn) = 5
   AND datepart(year, datecolumn) = 2013

Applying functions on columns is genrally a bad idea. It makes the condition non-sargable.

Better to test on an interval.

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

A SQL Fiddle to play around with that proves my point

Try

SELECT * FROM Table WHERE month = DATE_FORMAT('2013-05-07 10:18:00', '%m') AND ...

I imagine your column is itself a DATE? Then you need to apply DATEPART on both sides of the "="

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')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top