我正在爲數據倉庫生成[Dim_Calendar]表。我在下面開發了一個查詢,需要29秒來執行&插入27k行。如果可能,我想優化它。我明白,雖然循環不幫助性能,我不知道如何取代它來實現相同的結果。如何優化INSERT語句
我正在使用SQL Server 2012 BI版本。
IF EXISTS(SELECT * FROM sys.indexes WHERE name='PK_Dim_Calendar_1' AND object_id = OBJECT_ID('Dim_Calendar'))
BEGIN
ALTER TABLE [dbo].[Dim_Calendar] DROP CONSTRAINT [PK_Dim_Calendar_1]
END
SET DATEFIRST 1--Sets Monday as 1st day of the week.
DECLARE @today DATETIME = (SELECT GETDATE())
DECLARE @start DATETIME = DATEADD(dd, 1, (SELECT Max(date) FROM Dim_Calendar))
IF @start IS NULL
BEGIN
INSERT INTO [dbo].[Dim_Calendar]
VALUES (19000101, '1900-01-01', 'Monday', 1 ,'Unknown', 1, 'January', 1900, 1)
SET @start = '1940-01-01'
END
DECLARE @end DATETIME = (SELECT DATEFROMPARTS(YEAR(@today), 12, 31))
WHILE @start <= @end
BEGIN
INSERT INTO [dbo].[Dim_Calendar]
SELECT
YEAR(@start) * 10000 + MONTH(@start) * 100 + DAY(@start)
,@start
,DATENAME(dw, @start)
,DATEPART(wk, @start)
,'w/c ' + CONVERT(char(8), DATEADD(dd, 1 - DATEPART(dw, @start), @start), 3)
,DATEPART(mm, @start)
,DATENAME(MONTH, @start)
,YEAR(@start)
,DATEPART(QQ, @start)
SET @start = DATEADD(dd, 1, @start)
END
ALTER TABLE [dbo].[Dim_Calendar] ADD CONSTRAINT [PK_Dim_Calendar_1] PRIMARY KEY CLUSTERED
(
[FullDateID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
這是14慢於Numbers表格的小數字慢了大量的時間,35倍,按[阿龍貝特朗的基準(HTTP ://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-2)。你已經用循環替換循環,但是你仍然產生一個沒有索引好處的值 – 2014-10-30 10:24:23
@PanagiotisKanavos OP要求加快插入速度的方法,這可能不是最快的方法,但是在我的開發箱中仍然只花了643毫秒才能完成,這比他的29秒要快得多。 – 2014-10-30 10:34:29