Menu

Tuesday, 29 March 2011

To Get only Date from datetime in Sql server

Unfortunately, In Sql server there is no such predefined function available. Now we have to achieve that one by creating one simple user defined function like this.

CREATE FUNCTION DateOnly(@DateTime datetime) 
--Returns only the date by removing the time 
RETURNS datetime 
AS 
BEGIN 
 return dateadd(dd,0,datediff(dd,0,@DateTime)) 
END

How to Usage this function in queries:

For this i will create one table with following columns. Those are
--Create Table with one column with datetime data type
create table TestTable(DateInfo datetime)

After that i will insert one record in the similar way

insert into TestTable(DateInfo) values(getdate())

--Normal Query
select DateInfo from TestTable   --Output is: 2011-03-29 11:50:06.487

--To Get the only Date by using above function
select dbo.dateonly(DateInfo) as OnlyDateInfo from TestTable   --Output is :2011-03-29 00:00:00.000





No comments:

Post a Comment