'How to run series of values through stored procedure

I have a stored procedure that I need to run a list of values through and output into a temp table.

This is the SP: EXEC [SP_ReturnHTML] @zoneid, 1

The first value, I assume, will be a variable and the second value will be hard-coded. I am not able to modify this SP, as it is used in other processes, so I need to run these values through the SP via a cursor or WHILE loop. The values only need to be run through once, so a FAST_FORWARD cursor type may be more ideal, based on some preliminary reading on cursors (of which my experience in is extremely limited). This is what I attempted:

declare @zoneid int = (select zoneid from #values)
declare list cursor fast_forward
for EXEC [SP_ReturnHTML] @zoneid,1
open list
fetch next from list

But when I try to do this, I get the error Incorrect syntax near the keyword 'EXEC'.

The output of this SP, when using @zoneid=14105 (and the hard-coded 1 relates to the fieldgroupid) looks something like the shot below. For clarity, despite using @zoneid=14105, the reason a value of 4054 shows up is due to the way the SP is written, and is intended. The two values relate to a state and county relationship, noted by the first 2 columns, ParentHeaderId and HeaderId. I opted to use 14105 for the example, because the 3 examples in the #values table only retrieve their secondary value and I wanted to avoid confusion here.

enter image description here

The values that I need to run through the SP for the @zoneid are in a table (which has about 3100 rows), which can be exemplified with the following:

create table #values (zoneid int)  
insert into #values 
values
(13346),
(13347),
(13348)

So very simply put, I need something like the following as a final product (pseudo code):

declare @zoneid INT = (select zoneid from #values)
select * into #results from 
(
EXEC [SP_ReturnHTML] @zoneid, 1
)


Solution 1:[1]

Something like this:

drop table if exists #results 
drop table if exists #Data
go

create or alter procedure [SP_ReturnHTML] @value int, @s varchar(20)
as
begin
  select concat(' value=',@value, '; s = ', @s) 
end

go

create table #Data (value int, county varchar(30))
insert into #Data 
values
(100, 'Baker'),
(101,'Baldwin'),
(102,'Baldwin'),
(103,'Ballard'),
(104,'Baltimore City'),
(105,'Baltimore'),
(106,'Bamberg'),
(107,'Bandera'),
(108,'Banders'),
(109,'Banks'),
(110,'Banner'),
(111,'Bannock'),
(112,'Baraga')

go

create table #results(value nvarchar(200))
declare c cursor local for select value from #Data
declare @value int
open c
fetch next from c into @value
while @@fetch_status = 0
begin
  insert into #results(value)
  EXEC [SP_ReturnHTML] @value, '1'

  fetch next from c into @value
end

go

select *  
from #results 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Browne - Microsoft