I have written a sql that select data between a date and a another.
Basically the problem is about the date format that i wanted to made some selection
My coloum name is date_tm and sample data like this: 2011-04-04 00:30:19.107
My Sql like this:
DECLARE @Date_From DATETIME;
DECLARE @Date_To DATETIME;
SET @Date_From = CONVERT(VARCHAR(10),DATEADD(d,DATEDIFF(d,0,GETDATE()),0)-1,120);
SET @Date_To = CONVERT(VARCHAR(10),DATEADD(d,DATEDIFF(d,0,GETDATE()),0)-1,120);
select distinct no, lot
from database.dbo.TblName
Where Convert(varchar(10), Date_Tm, 120) Between '@Date_From' And '@Date_To';
I try to debug it using this
Print(@Date_From);
Print(@Date_To);
The output is something like this “Nov 6 2011 12:00AM” am i not convert its alreadly?
and then i tested with select statement like this:
select CONVERT(VARCHAR(10),DATEADD(d,DATEDIFF(d,0,GETDATE()),0)-1,120);
The output is something like this “2011-11-06” why its work here?
Select result is nothing ==”
Then i do a lot of testing regarding this date format
I try to direct parse in date_from and Date_to
where Convert(varchar(10), Date_Tm, 120) Between '2011-04-04' And '2011-04-04'
I get what is expected
Anyway,what i wanted is get data by a range of date.I am crushing my head with this convert method ==”
Please help me.
Thanks:
PS:Please dont hesitate to voice out my mistake. we all learn from mistake and sorry for my poor english.
Regards:
LiangCk
It is because you are declaring your two variables as datetime instead of varchar(10). SQL is automatically converting it back to datetime because your variables are datetime.