Wednesday, March 7, 2012

how to compare current date with sql db datetime data type

Hi,

I am using one datetime data type ( name: date_added ) and getdate() as default value. I want to display only those records added today. How I can compare current date with date_added.

Thanks
ManojSELECT * FROM tablename WHERE CONVERT(varchar(10),date_added,112)=CONVERT(varchar(10),GetDate(),112)

This converts both dates to yyyymmdd format, and then compares them. A better alternative might be:

SELECT * FROM tablename WHERE date_added>=CONVERT(datetime,CONVERT(varchar(10),GetDate(),112))

This presumes that there are no records added later than today. It compares the date_added to getdate() return value, converted to yyyymmdd, then converted back to a date.

No comments:

Post a Comment