Subject | SP to extract a week number |
---|---|
Author | rvellacott@passfield.co.uk |
Post date | 2001-11-14T11:23:06Z |
Here in case anyone wants to use it, is a procedure to extract a week
number, in the form 'yyyy/ww', and assuming weeks begin on Mondays.
Can anyone make it more efficient or less inelegant?
CREATE PROCEDURE GET_WEEK
(
D TIMESTAMP
)
RETURNS
(
WEEK_NO VARCHAR(8)
)
AS
declare variable DAYNUM INTEGER;
declare variable WK1BEGINS DATE;
declare variable YEARNUM INTEGER;
declare variable YEAR_BEGINS DATE;
declare variable WEEKSTR CHAR(2);
declare variable WEEKNUM integer;
declare variable WEEK1_FOUND char(1);
BEGIN
YEARNUM = EXTRACT (YEAR FROM D);
WEEK1_FOUND = 'F';
WHILE (WEEK1_FOUND <> 'T') DO
BEGIN
WK1BEGINS = CAST('01/01/'||CAST(YEARNUM AS CHAR(4)) AS DATE);
while (EXTRACT(WEEKDAY FROM WK1BEGINS) <> 1) DO
WK1BEGINS = WK1BEGINS + 1;
IF (D < WK1BEGINS) THEN
YEARNUM = YEARNUM -1;
ELSE
WEEK1_FOUND = 'T';
END
WEEKNUM = CAST(((D-WK1BEGINS)/7)+0.5 AS INTEGER);
IF (WEEKNUM < 10) THEN
WEEKSTR = '0'||CAST(WEEKNUM AS CHAR(1));
ELSE
WEEKSTR = CAST(WEEKNUM AS CHAR(2));
WEEK_NO = CAST(YEARNUM AS CHAR(4))||'/'||WEEKSTR;
END
number, in the form 'yyyy/ww', and assuming weeks begin on Mondays.
Can anyone make it more efficient or less inelegant?
CREATE PROCEDURE GET_WEEK
(
D TIMESTAMP
)
RETURNS
(
WEEK_NO VARCHAR(8)
)
AS
declare variable DAYNUM INTEGER;
declare variable WK1BEGINS DATE;
declare variable YEARNUM INTEGER;
declare variable YEAR_BEGINS DATE;
declare variable WEEKSTR CHAR(2);
declare variable WEEKNUM integer;
declare variable WEEK1_FOUND char(1);
BEGIN
YEARNUM = EXTRACT (YEAR FROM D);
WEEK1_FOUND = 'F';
WHILE (WEEK1_FOUND <> 'T') DO
BEGIN
WK1BEGINS = CAST('01/01/'||CAST(YEARNUM AS CHAR(4)) AS DATE);
while (EXTRACT(WEEKDAY FROM WK1BEGINS) <> 1) DO
WK1BEGINS = WK1BEGINS + 1;
IF (D < WK1BEGINS) THEN
YEARNUM = YEARNUM -1;
ELSE
WEEK1_FOUND = 'T';
END
WEEKNUM = CAST(((D-WK1BEGINS)/7)+0.5 AS INTEGER);
IF (WEEKNUM < 10) THEN
WEEKSTR = '0'||CAST(WEEKNUM AS CHAR(1));
ELSE
WEEKSTR = CAST(WEEKNUM AS CHAR(2));
WEEK_NO = CAST(YEARNUM AS CHAR(4))||'/'||WEEKSTR;
END