Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 3

Date and Time Manipulation in SQL Server 2000

By Manuj Bahl
Tell a Friend
Published: 6/8/2004
Reader Level: Beginner Intermediate Rate this Article
Rated: 4.60 by 20 member(s).
Printable Version
Discuss in the
Forums
declare @datevar datetime
select @datevar = getdate()

/*Example for getdate() : getting current datetime*/


select getdate() [Current Datetime]

/*Example for dateadd : getting date 7 days from current datetime*/


select dateadd(dd, 7, @datevar) [Date 7 days from now]

/*Example for datediff : getting no of days passed since 01-01-2004*/


select datediff(dd,'20040101',@datevar) [No of days since 01-01-2004]

/*Example for datename : getting month name*/


select datename(mm, @datevar) [Month Name]

/*Example for datepart : getting week from date*/


select datepart(wk, @datevar ) [Week No]

/*Example for day : getting day part of date*/


select day (@datevar) [Day]

/*Example for month : getting month part of date*/


select month(@datevar) [Month]

/*Example for year : getting year part of date*/


select year(@datevar) [Year]
Now I will provide you with some code samples which you can use for various tasks. I
will try to include as many examples I can think of, but this list is not exhaustive:

1. To find the first day of a month:

select dateadd(dd,-(day(DateColumn)-1),DateColumn)
2. To find last day of a month:

select dateadd(dd,-
(day(dateadd(mm,1,DateColumn))),dateadd(mm,1,DateColumn))
3. To find birthdays in next seven days:

use pubs

go

/* Creating a Test Table */


Create Table MyDateTest99
(
Birthday datetime
)
go
/* Inserting the test value into the table */
insert into MyDateTest99 select convert (varchar(10),'19780129',120)
insert into MyDateTest99 select convert (varchar(10),'19670821',120)

You might also like