你不需要這個以「循環」的方式運行。你可以只使用一個公用表表達式生成行,與儘可能多的行每財產有在產權車庫:
with GarageRows as (
select id
, garagecount
, 0 [counter]
from Properties
union all
select p.id
, 1
, gr.counter + 1
from GarageRows gr
inner join Properties p on gr.id = p.id
where gr.counter + 1 < p.garagecount)
insert into Garages(PropertyID)
select gr.ID
from GarageRows gr
where gr.garagecount > 0
如果你只是想測試上面的CTE的結果,你可以運行下面的查詢,該查詢生成兩個屬性的行,一個包含2個車庫,另一個包含4個車庫。
declare @properties table (id int, garagecount int)
insert @properties values (1, 2), (2, 4)
;with GarageRows as (
select id
, garagecount
, 0 [counter]
from @Properties
union all
select p.id
, 1
, gr.counter + 1
from GarageRows gr
inner join @Properties p on gr.id = p.id
where gr.counter + 1 < p.garagecount)
select gr.ID
from GarageRows gr
where gr.garagecount > 0
order by gr.ID
所以,如果您的查詢返回'1 ,4',你想四次插入'1'? – HoneyBadger
這就是我正在尋找的。 – Daniel