This code is derived from a useful article by Todd Fifield at SQLServerCentral.com and has been modified to include columns based on the ISO8601 date and times standard (here and here).
IF OBJECT_ID('dbo.CalendarDay') IS NOT NULL
DROP TABLE dbo.CalendarDay;
GO
CREATE TABLE CalendarDay
( DayID INT IDENTITY(1, 1)
, DayDate SMALLDATETIME
, WeekNumber INT
, OrdinalDate VARCHAR(8)
, DateWeekNumber VARCHAR(10)
, DayNumber INT
, NameOfDay VARCHAR(10)
)
GO
SET NOCOUNT ON;
DECLARE
@Date SMALLDATETIME;
SET DATEFIRST 1; --assuming start of week is monday
SET @Date = '2010-01-01';
WHILE @Date < '2011-01-01'
BEGIN
INSERT INTO CalendarDay
( DayDate, WeekNumber, OrdinalDate, DateWeekNumber, DayNumber, NameOfDay )
SELECT @Date
, (DATEPART(WK, @Date))
, CAST(DATEPART(YEAR, @Date) as VARCHAR) + '-' + CAST(DATEPART(DY, @Date) as VARCHAR)
, CAST(DATEPART(YEAR, @Date) as VARCHAR) + '-'
+ 'W' + CAST(DATEPART(WK, @Date) as VARCHAR) + '-'
+ CAST(DATEPART(WEEKDAY, @Date) as VARCHAR)
, DATEPART(WEEKDAY, @Date)
, CASE DATEPART(WEEKDAY, @Date)
WHEN 1 THEN 'Monday'
WHEN 2 THEN 'Tuesday'
WHEN 3 THEN 'Wednesday'
WHEN 4 THEN 'Thursday'
WHEN 5 THEN 'Friday'
WHEN 6 THEN 'Saturday'
ELSE 'Sunday' END;
SET @Date = DATEADD(day, 1, @Date);
END
GO
Showing posts with label Year. Show all posts
Showing posts with label Year. Show all posts
Tuesday, 17 August 2010
Auxiliary Calendar table - SQL
Labels:
Auxiliary,
Calendar table,
Cast,
CREATE TABLE,
Date and Time,
DateAdd,
Datepart,
Dates,
DROP TABLE,
DY,
ISO 8601,
SQL,
Weekday,
WK,
Year
Friday, 30 October 2009
Get last day of month - CR
local numbervar thismonth := Month(CurrentDate)+1;
local numbervar thisyear := Year(CurrentDate);
local datevar endday;
endday := Date(thisyear, thismonth, 1)-1; //get the last day of the month
local numbervar thisyear := Year(CurrentDate);
local datevar endday;
endday := Date(thisyear, thismonth, 1)-1; //get the last day of the month
Get first day of month - CR
local numbervar thismonth := Month(CurrentDate);
local numbervar thisyear := Year(CurrentDate);
local datevar startday;
startday := Date(thisyear, thismonth, 1); //get the first day of the month
local numbervar thisyear := Year(CurrentDate);
local datevar startday;
startday := Date(thisyear, thismonth, 1); //get the first day of the month
Subscribe to:
Posts (Atom)