我想在存儲過程中實時填充日期時間列。下面是我目前所做的查詢,但會降低查詢性能。填充日期時間列
CREATE TABLE #TaxVal
(
ID INT
, PaidDate DATETIME
, CustID INT
, CompID INT
)
INSERT INTO #TaxVal(ID, PaidDate, CustID, CompID)
VALUES(01, '20150201',12, 100)
, (03,'20150301', 18,101)
, (10,'20150401',19,22)
, (17,'20150401',02,11)
, (11,'20150411',18,201)
, (78,'20150421',18,299)
, (133,'20150407',18,101)
-- SELECT * FROM #TaxVal
DECLARE @StartDate DATETIME = '20150101'
, @EndDate DATETIME = '20150501'
DECLARE @Tab TABLE
(
CompID INT
, DateField DATETIME
)
DECLARE @T INT
SET @T = 0
WHILE @EndDate >= @StartDate + @T
BEGIN
INSERT INTO @Tab
SELECT CompID
, @StartDate + @T AS DateField
FROM #TaxVal
WHERE CustID = 18
AND CompID = 101
ORDER BY DateField DESC
SET @T = @T + 1
END
SELECT DISTINCT * FROM @Tab
DROP TABLE #TaxVal
哪種編寫此查詢的最佳方法是爲了獲得更好的性能?
嘗試一個公用表表達式(CTE)或使用_numbers table_來生成一組日期並一次插入它們。搜索** sql服務器生成日期**應該讓你開始。提示:使用適當的軟件(MySQL,Oracle,DB2,...)和版本(例如, '的SQL服務器2014'。語法和功能的差異往往會影響答案。 – HABO
能否請您舉個例子。謝謝 – dLight