Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL Server
Expertise: Beginner
Jul 20, 2000

Date Time Fields

Question:
I have a database with a DateTime field of the following structure 1974-01-18T00:00:00'. How do I query it so that I can extract the dates with a particular day and month but any year?

Answer:
The datepart function in SQL will retrieve a portion of the date:

create table datesearch
(
	mydate datetime
)
go
insert into datesearch values ('01/01/2000')
insert into datesearch values ('01/02/2000')
insert into datesearch values ('01/03/2000')
insert into datesearch values ('02/01/2000')
insert into datesearch values ('02/02/2000')
insert into datesearch values ('02/03/2000')
go
select *
from datesearch
where datepart(dd,mydate) = 2
It will return only the rows where mydate falls on the second day of the month.

However, before writing such a query, you should consider the performance you will get from it. In order to test the performance, I created a sample table and populated it with 500,000 rows:

set nocount on
go

drop table datesearch
go
create table datesearch
(
	id int identity(1,1) not null
	constraint pk_datesearch primary key(id),
	invoicedate datetime,
	clientid  int,
	amount numeric (9,2)
)
go

declare @i int, @invoicedate datetime,@clientid int, @amount numeric(9,2)
select @i = 0
while @i < 500000
begin
	select @invoicedate = dateadd(dd,cast (rand() * 5000 as int),getdate())
	select @clientid = cast(rand() * 500 as int)
	select @amount = rand() * 500000
	insert into datesearch(invoicedate,clientid,amount)
	values			(@invoicedate,@clientid,@amount)
	select @i = @i + 1
end
		
go

create index ak_datesearch_invoicedate on datesearch(invoicedate)
I then used the following two queries to compare the statistics and the showplan:
select count(*)
from datesearch
where
datepart(dd,invoicedate) = 20

select count(*)
from datesearch
where
invoicedate between '10/01/2000' and '12/01/2000'
The query that used datepart performed a table scan while the second query used the index on invoicedate. If you find that you are suffering a performance hit, you might choose to add another column to your table to represent just the day of the month (or whatever other value) you are searching on and index it. This is different than adding a computed column because in version 7 you can't index on a computed column.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date