Thursday, May 25, 2006

Populating A Dropdown With Weekly Dates

Let's assume you have a website and the user can pick from a date range, You want to be a nice guy/girl (* reason for the asterisk is at the end) so instead of having a dropdown that looks like

Week1
Week2
Week3

You want it to have start and end dates for the week
The start date should be a Sunday and the end date should be a Saturday
The output should be something like this

2006-05-07 - 2006-05-13
2006-05-14 - 2006-05-20
2006-05-21 - 2006-05-27

What do you do? Do you store all these dates in a table, you can but you will have to maintain this.
Another way is to use a number table
You would create the number table only once. Then you can use DATEADD and DATEPART with the number table to return the desired results


-- Create out Pivot table ** do this only once-- populate it with 1000 rows
CREATE TABLE NumberPivot (NumberID INT PRIMARY KEY)

DECLARE @intLoopCounter INT
SELECT @intLoopCounter =0

WHILE @intLoopCounter <=1000 BEGIN
INSERT INTO NumberPivot
VALUES (@intLoopCounter)

SELECT @intLoopCounter = @intLoopCounter +1
END
GO

--And here is the query

--I started with a Sunday
DECLARE @StartDate DATETIME
SELECT @StartDate ='05/07/2006'

--How many rows to return
DECLARE @RowsToReturn INT
SELECT @RowsToReturn = 50

SELECT DATEADD(wk,numberID,@StartDate) AS WeekStart,
DATEADD(dd,-1,(DATEADD(wk,numberID+1,@StartDate))) AS WeekEnd
FROM dbo.NumberPivot
WHERE NumberID <= @RowsToReturn -1 -- 1 since the number table starts from 0
AND DATEADD(wk,numberID,@StartDate) >=@StartDate
ORDER BY 1


* At my previous job we were doing file exchanges with some state agencies. One of the fields in the file was Sex and the values could be either F or M,. fair enough right? Well guess what, there was one person who worked there and had a sex-operation done and did not want to be classified as male or female So we then added other ( O ) We had no choice this was specifically written for the state and they were the major user of the program…oh well, nothing is black or white is it?

No comments:

Post a Comment