table1とtable2の関係はあまり明確ではありません。以下のクエリでは、必要に応じて表2のlicenseIDを更新する必要があります。
create table #tmp1
(
LicenseID int,
CompanyWindowId int,
CompanyCount int
)
GO
create table #tmp2
(
LicensedCompanyID int identity,
CompanyWindowId int,
CompanyID int,
LicenseID int
)
GO
insert into #tmp1 values (9,9,5),(12,9,2)
insert into #tmp2 (CompanyWindowId,CompanyID) values (9,10),(10,12),(10,14),(10,15),(10,16),(10,17),(10,18)
SELECT * from #tmp2
declare @licenseID int
declare @count int=1
declare @count2 int=1
declare @recordcount int
declare @CompanyCount int
select @recordcount=count(1) from #tmp1
WHILE @count2<[email protected]
BEGIN
select @licenseID=LicenseID,@CompanyCount=CompanyCount FROM (select *, row_number() over (order by licenseID) RID from #tmp1)T where [email protected]
SET @count=1
WHILE @CompanyCount>[email protected]
BEGIN
SET ROWCOUNT 1
UPDATE #tmp2 SET [email protected] WHERE LicenseID IS NULL
SET @count+=1
END
SET @count2+=1
END
SET ROWCOUNT 0
SELECT * from #tmp2
drop table #tmp1
drop table #tmp2