【发布时间】:2021-03-27 15:42:25
【问题描述】:
我有以下代码循环遍历具有唯一型号的表并创建一个新表,其中每个型号都包含基于年份和周数的行。我怎样才能翻译它,使它不使用光标?
DECLARE @current_model varchar(50);
--declare a cursor that iterates through model numbers in ItemInformation table
DECLARE model_cursor CURSOR FOR
SELECT model from ItemInformation
--start the cursor
OPEN model_cursor
--get the next (first value)
FETCH NEXT FROM model_cursor INTO @current_model;
DECLARE @year_counter SMALLINT;
DECLARE @week_counter TINYINT;
WHILE (@@FETCH_STATUS = 0) --fetch status returns the status of the last cursor, if 0 then there is a next value (FETCH statement was successful)
BEGIN
SET @year_counter = 2019;
WHILE (@year_counter <= Datepart(year, Getdate() - 1) + 2)
BEGIN
SET @week_counter = 1;
WHILE (@week_counter <= 52)
BEGIN
INSERT INTO dbo.ModelCalendar(
model,
sales_year,
sales_week
)
VALUES(
@current_model,
@year_counter,
@week_counter
)
SET @week_counter = @week_counter + 1
END
SET @year_counter = @year_counter + 1
END
FETCH NEXT FROM model_cursor INTO @current_model
END;
CLOSE model_cursor;
DEALLOCATE model_cursor;
如果 ItemInformation 包含下表:
model,invoice
a,4.99
b,9.99
c,1.99
d,8.99
那么预期的输出是:
model,sales_year,sales_week
A,2019,1
A,2019,2
A,2019,3
...
A,2019,52
A,2020,1
A,2020,2
A,2020,3
...
A,2020,51
A,2020,52
A,2020,53 (this is 53 because 2020 is leap year and has 53 weeks)
A,2021,1
A,2021,2
...
A,2022,1
A,2022,2
...
A,2022,52
B,2019,1
B,2019,2
...
D, 2022,52
【问题讨论】:
-
您能否展示一些示例数据(如 DDL/DML)和预期结果。
-
你不需要游标,你只需要一个日历表的交叉连接。第 1 步:创建一个包含所有年份和周数的表格。
-
@Nick.McDermaid 是的,我在另一个标签上打开了它。这是我迷路的地方:
'UPDATE STATISTICS '+QUOTENAME([name]) AS sql_code。我对 SQL 思维过程很陌生 -
@kindofhungry 我添加了另一个使用更基本 SQL 的解决方案 - 我讨厌看到有人在 SQL 中使用循环 :) 我很想知道它是否有效。