0

I've the query below:

select * from tblA

This tblA have column ID and NAME

I want get the ID's from this table and use into a procedure.

I.E:

exec spGet ID

This is a loop, right?

How I can do this?

Tnks.

jsfelipearaujo
  • 25
  • 1
  • 10
  • you need comma separated list of ID's ? – Jaydip Jadhav Aug 22 '16 at 12:41
  • the query by itself would return a record set object containing all the fields in the table. if you modified it to select id from tblA you would get a recordset from the database that could then be "looped" in code outside of SQL server... Why do you need a loop? how is the data being used? are you using .net or some other language to query the database? – xQbert Aug 22 '16 at 12:43
  • [How do I execute a stored procedure once for each row returned by query?](http://stackoverflow.com/questions/886293/how-do-i-execute-a-stored-procedure-once-for-each-row-returned-by-query) / [SQL - Call Stored Procedure for each record](http://stackoverflow.com/questions/2077948/sql-call-stored-procedure-for-each-record) – Alex K. Aug 22 '16 at 12:44

1 Answers1

0

If you really want to do it this way, you can use a cursor, but I'd strongly suggest to rethink what you're doing.

DECLARE @ID INT;

DECLARE curIteration CURSOR
FOR
    SELECT ID
    FROM tblA;

OPEN curIteration
FETCH NEXT FROM curIteration
INTO @ID;

WHILE @@FETCH_STATUS = 0
BEGIN
    EXECUTE spGet @ID;

    FETCH NEXT FROM curIteration
    INTO @ID;
END

CLOSE curIteration;
DEALLOCATE curIteration;
Evaldas Buinauskas
  • 13,739
  • 11
  • 55
  • 107