¿Cómo encontrar datos para todo el mes para el formato de fecha dd/mm/yyyy?
Frecuentes
Visto 3,181 veces
0
I have a database with date format "yyyyymmdd' and data-type varchar(8). In this case when I need to find a data for whole month I used to write code like below :
select * from table1
where Date Between (convert(varchar(6),getdate(),112)+'01')
AND (convert(varchar(6),getdate(),112)+'31'))
Now I just have a new table with date format "dd/mm/yyyy" and date type varchar(10) and I would like to extract data from the table for whole month without specifying exact date. I want start date as first day of current and month and end date as last day of the current month.
But I don't now how to do the same as the date format is now 'dd/mm/yyyy'.
2 Respuestas
2
First, thing you should store you date as the datatype of date
y no varchar
Puedes usar MONTH()
SELECT *
FROM yourTable
WHERE MONTH(convert(datetime, dt, 103)) = MONTH(getdate()) -- or month you want
or DATEPART()
SELECT *
FROM yourTable
WHERE DatePart(month, convert(datetime, dt, 103)) = DatePart(month, getdate())
Ver Violín SQL con demostración
Both of these, get the value of the MONTH()
-- 8, 9, 10 -- and then compares it to the month that you want.
Respondido 28 ago 12, 12:08
thanks blueffeet .... it works perfect..but I wonder if it can also be written in the similar way I have written for format 'yyyymmdd' in the original question. - user1449596
@user1449596 you still should be able to use it for dates in the format yyyymmdd
- Taryn
Note that applying month and datepart to the column will mean that an index can't be used (not that an index on d/m/y would be very useful at all). But if the data type gets fixed it will be much better to say >= {month} and < {month + 1}. - Aarón Bertrand
Thanks bluefeet..will i need to change the code for next year? @Aaron Bertrand..I will try to change data type as soon as possible. Thank you too. - user1449596
@ user1449596 el getdate()
will always have today's date so that will not have to change - Taryn
2
Muestra
select idcol,namecol,datecol, from table where datepart(mm,datecol)='9'
Edit:
select * from dummy where datepart(mm,dob)= datepart(mm,getdate())
http://sqlfiddle.com/#!3/50efd/7
Their is posibility of same month with different year so you also you need to takecare of year some like by adding and datepart(yyyy,dob)=datepart(yyyy,getdate())
Respondido 28 ago 12, 13:08
@satinder..in this case...I will need to manually specify month every month. I have an update store procedure and I want it to update on executing for whole month automatically without specifying month name. - user1449596
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas sql-server-2005 or haz tu propia pregunta.
Why is your date stored as a varchar? I suggest you fix it. - Aaron Bertrand