declare @loop int
declare @LocationId int
How to iterate in Stored Procedures?
How to Loop through in SPs in Sql server?
declare @Locations TABLE (LocationId int,ID int identity)
insert into @Locations (LocationId) SELECT ......
set @loop = (select min(Id) from @Locations)
WHILE @loop IS NOT NULL
select @LocationId = LocationId from @Locations where id = @loop
insert into #CustomersSelectedThisWeek
select top 200 LocationId,PostalCode,COUNT(PostalCode) from #State where LocationId= @LocationId group by locationid, postalcode order by COUNT(PostalCode)desc
set @loop = (Select min(Id) from @Locations where Id > @loop )