SQL Call Stored Procedure for each Row without using a cursor

Johannes Rudolph picture Johannes Rudolph · Nov 1, 2009 · Viewed 218.9k times · Source

How can one call a stored procedure for each row in a table, where the columns of a row are input parameters to the sp without using a Cursor?

Answer

Mark Powell picture Mark Powell · May 29, 2011

Generally speaking I always look for a set based approach (sometimes at the expense of changing the schema).

However, this snippet does have its place..

-- Declare & init (2008 syntax)
DECLARE @CustomerID INT = 0

-- Iterate over all customers
WHILE (1 = 1) 
BEGIN  

  -- Get next customerId
  SELECT TOP 1 @CustomerID = CustomerID
  FROM Sales.Customer
  WHERE CustomerID > @CustomerId 
  ORDER BY CustomerID

  -- Exit loop if no more customers
  IF @@ROWCOUNT = 0 BREAK;

  -- call your sproc
  EXEC dbo.YOURSPROC @CustomerId

END