我想在存储过程中动态填充日期时间列。下面是我目前所拥有的查询,但会降低查询性能。
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
编写此查询以获得更好性能的最佳方法是什么?
答案 0 :(得分:1)
改变这个:
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
到此:
;with cte as(
select cast('20150101' as date) as d
union all
select dateadd(dd, 1, d) as d from cte where d < '20150501'
)
INSERT INTO @Tab
SELECT CompID, d
FROM #TaxVal
cross join cte
WHERE CustID = 18 AND CompID = 101
Option(maxrecursion 0)
这是recursive common table expression
以获取范围内的所有日期。然后你做一个cross join
并插入。请注意,插入时订单集没有任何意义。
答案 1 :(得分:0)
Giorgi的答案
;with cte as(
select cast('20150101' as date) as d
union all
select dateadd(dd, 1, d) as d from cte where d < '20150501'
)
INSERT INTO @Tab
SELECT CompID, d
FROM #TaxVal
cross join cte
WHERE CustID = 18 AND CompID = 101
会起作用,但要小心递归CTE。如果日期范围很大,您将很快达到最大递归级别。通常,数字表的使用方式与HABO提到的非常相似。这只是一个包含单个列的表,只有一个整数,因此行可以是1,2,3,4,5等。然后,您可以加入Numbers表(外部应用适用于此)并使用数字dateadd获取增量日期。另请注意,您可能会遇到一个问题,即Numbers表格中没有足够的行包含您的日期范围。