Thursday, 5 June 2014

Extracting Date from Datetime Expression or Datetime Field in SQL Server

Use Convert() Function. From MSDN, this is the syntax:

Syntax for CONVERT: CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

To get it from a datetime expression,

Select Convert(varchar(10),GetDate(),111)

or from a field,

Select Convert(varchar(10),SomeField(),111)

So that when you perform a query with a criteria, you may write it like this:

Select convert(varchar(10),somefield(),111) between '2012/01/01' and '2012/01/10'


A little bit of explanation:

The convert() function needs 3 parameters to work but it can even without the last parameter. The example below gives a default date in string format.
Select Convert(varchar(10),GetDate()) ;
go

>Jan 19 201

While adding a style 111 (with century in japan format) in the last parameter for example would yield result like:
Select Convert(varchar(10),GetDate(),111) ;
go

>2012/01/19
And this will just be a perfect practice for obtaining the date only from a datetime expression.


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...