建立時間維度表的預存程序

來源:互聯網
上載者:User

在網上找到一個產生時間維度表的預存程序,挺好用的。放到這裡來,怕以後忘了。

create PROCEDURE [dbo].[Create_time_by_day_dimension]

    -- Add the parameters for the stored procedure here

AS

BEGIN

    -- SET NOCOUNT ON added to prevent extra result sets from

    -- interfering with SELECT statements.

SET NOCOUNT ON;

begin try

drop table [time_by_day_dimension]

end try

begin catch

end catch

CREATE TABLE [dbo].[time_by_day_dimension] (

  [time_id] [int] IDENTITY (1, 1) NOT NULL ,

  [the_date] [datetime] NULL ,

  [the_day] [nvarchar] (15) NULL ,

  [the_month] [nvarchar] (15) NULL ,

  [the_year] [smallint] NULL ,

  [day_of_month] [smallint] NULL ,

  [week_of_year] [smallint] NULL ,

  [month_of_year] [smallint] NULL ,

  [quarter] [nvarchar] (2) NULL ,

  [fiscal_period] [nvarchar] (20) NULL

) ON [PRIMARY]

DECLARE @WeekString varchar(12),

@dDate SMALLDATETIME,

@sMonth varchar(20),

@iYear smallint,

@iDayOfMonth smallint,

@iWeekOfYear smallint,

@iMonthOfYear smallint,

@sQuarter varchar(2),

@sSQL varchar(100),

@adddays int

SELECT @adddays = 1 --日期增量(可以自由設定)

SELECT @dDate = '01/01/2006' --開始日期

WHILE @dDate < '12/31/2010' --結束日期

BEGIN

  SELECT @WeekString = DATENAME (dw, @dDate)

  SELECT @sMonth=DATENAME(mm,@dDate)

  SELECT @iYear= DATENAME (yy, @dDate)

  SELECT @iDayOfMonth=DATENAME (dd, @dDate)

  SELECT @iWeekOfYear= DATENAME (week, @dDate)

  SELECT @iMonthOfYear=DATEPART(month, @dDate)

  SELECT @sQuarter = 'Q' + CAST(DATENAME (quarter, @dDate)as varchar(1))

  INSERT INTO time_by_day_dimension(the_date, the_day, the_month, the_year,

  day_of_month,

  week_of_year, month_of_year, quarter) VALUES

  (@dDate, @WeekString, @sMonth, @iYear, @iDayOfMonth, @iWeekOfYear,

  @iMonthOfYear, @sQuarter)

  SELECT @dDate = @dDate + @adddays

END

END

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.