Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Application Security Testing: An Integral Part of DevOps

Date Time Fields

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?

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

create table datesearch
	mydate datetime
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')
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

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

declare @i int, @invoicedate datetime,@clientid int, @amount numeric(9,2)
select @i = 0
while @i < 500000
	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

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
datepart(dd,invoicedate) = 20

select count(*)
from datesearch
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.



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