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
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:
Syntax:
FOREACH (rowset_expression) AS FOR EACH ROW statement_list
Where:
rowset_expression
Specifies the table or query results to be traversedstatement_list
Specify the SQL statement to be executedUsage example:
The following example uses FOREACH to traverseCustomers
table and output the name and address for each customer:
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;
Note:
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!