kadang kita pingin bikin periode kalender dari tanggal berapa s/d berapa.
berikut scriptnya. Tapi hanya berlaku mulai SQL 2005 Server.
di sql server 2000 tidak bisa (harus dengan cara lain).
1.) bikin tabel kalender dulu,
berikut scriptnya
create table kalender
(
no int identity(1,1) not null,
[date] datetime not null,
)
2.) bikin funcion yang namanya 'tabeltanggal' yang akan generate periode kalendernya
berikut scriptnya
CREATE FUNCTION [dbo].[tabeltanggal]
(
@FirstDate datetime,
@LastDate datetime
)
RETURNS @datetable TABLE (
[date] datetime
)
AS
BEGIN
SELECT @FirstDate = DATEADD(dd, 0, DATEDIFF(dd, 0, @FirstDate)); SELECT @LastDate = DATEADD(dd, 0, DATEDIFF(dd, 0, @LastDate));
WITH CTE_DatesTable
AS
(
SELECT @FirstDate AS [date]
UNION ALL
SELECT DATEADD(dd, 1, [date])
FROM CTE_DatesTable
WHERE DATEADD(dd, 1, [date]) <= @LastDate
)
INSERT INTO @datetable ([date])
SELECT [date] FROM CTE_DatesTable
OPTION (MAXRECURSION 0)
RETURN
END
3.) bikin script untuk generate periode kalender yang diinginkan
misal akan bikin kalender periode 01 desember 2010 s/d 10 desember 2010
yaitu sbb:
insert into kalender ([date])
select [date] from tabeltanggal('20101201', '20101210')
4.) silakan liat hasilnya di tabel kalender;
select * from kalender
Saturday, March 12, 2011
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment