Home > Database > Mysql Tutorial > How Can I Call a Stored Procedure for Each Row in a Table Without Cursors?

How Can I Call a Stored Procedure for Each Row in a Table Without Cursors?

Susan Sarandon
Release: 2025-01-06 00:03:40
Original
628 people have browsed it

How Can I Call a Stored Procedure for Each Row in a Table Without Cursors?

Calling a Stored Procedure for Each Row Without a Cursor

If you need to invoke a stored procedure for every row in a table, but wish to avoid using a cursor, you can utilize a set-based approach. Here's a code snippet to guide you:

-- 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
Copy after login

This code iterates over a table, retrieves the next customer's ID, and invokes the stored procedure YOURSPROC with the ID as the parameter. It continues this loop until there are no more customers to process.

The above is the detailed content of How Can I Call a Stored Procedure for Each Row in a Table Without Cursors?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template