Home > Database > SQL > body text

Usage of foreach in sql

下次还敢
Release: 2024-05-07 05:42:14
Original
1243 people have browsed it

The FOREACH statement in SQL is used to perform loop operations on multiple rows in a table, including traversing the rows in the table, performing operations for each row, and filtering rows based on conditions. The syntax is FOREACH (rowset_expression) AS FOR EACH ROW statement_list.

Usage of foreach in sql

Usage of FOREACH in SQL

The FOREACH statement is used in SQL to execute a series of rows in a table Loop operation. It is mainly used in the following scenarios:

  • Loop through multiple rows in the table
  • Perform one or more operations on each row
  • Filter rows based on conditions

Syntax:

<code>FOREACH (rowset_expression) AS FOR EACH ROW
  statement_list</code>
Copy after login

Where:

  • rowset_expression Specifies the table or query results to be traversed
  • statement_list Specify the SQL statement to be executed

Usage example:

The following example uses FOREACH to traverse Customers table and output the name and address for each customer:

<code class="sql">DECLARE @Customers TABLE (
  ID int,
  Name nvarchar(50),
  Address nvarchar(100)
);
INSERT INTO @Customers (ID, Name, Address) VALUES
  (1, 'John Doe', '123 Main Street'),
  (2, 'Jane Smith', '456 Oak Avenue');

FOREACH (row IN @Customers) AS FOR EACH ROW
  SELECT Name, Address FROM row;</code>
Copy after login

Note:

    ##FOREACH statement must be used within a BEGIN...END block .
  • rowset_expression can be a table variable, table expression, or query.
  • statement_list can contain any valid SQL statement, such as SELECT, INSERT, UPDATE, and DELETE.
  • FOREACH statement can also be used to handle cursors.

The above is the detailed content of Usage of foreach in sql. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template