sql四种循环结构应用举例

发布时间:2019-12-03编辑:脚本学堂
sql server中有四种循环结构,分别是:FOR循环、LOOP循环、WHILE循环、REPEAT循环,可分别用于遍历表中符合条件的每一行记录。

sql 四种循环结构,分别是:
FOR循环、LOOP循环、WHILE循环、REPEAT循环,可分别用于遍历表中符合条件的每一行记录。

sql server中没有for循环,不过可以用while来代替,具体请看:sql server for循环的问题

下面为大家介绍一个案例,分别使用这四种循环来实现。

要求:更新employee库,把所有北京籍员工的工资提高10%,哈哈,北京的朋友有福了。

例1:使用FOR循环
 

复制代码 代码示例:
CREATE PROCEDURE QGPL/TEST_FOR
LANGUAGE SQL
BEGIN
FOR each_record AS
---cur01 CURSOR FOR
------SELECT * FROM code,salary,city from employee where city="Beijing"
---------DO
------------UPDATE employee
------------SET salary=salary * 1.1
------------WHERE CURRENT OF cur01;
ENDFOR;
END;

例2:使用LOOP循环
 

复制代码 代码示例:

CREATE PROCEDURE QGPL/TEST_LOOP
LANGUAGE SQL
BEGIN
DECLARE code_v char(10);
DECLARE salary_v integer;
DECLARE city_v char(20);

DECLARE C1 CURSOR FOR
---SELECT code,salary,city FROM employee WHERE city="Beijing";
OPEN C1;
loop_label:
LOOP
- FETCH C1 INTO code_v,salary_v,city_v;
--IF SQLCODE=0 THEN
------SET salary_v=salary_v*1.1;
------UPDATE employee SET salary=salary_v
---------WHERE CURRENT OF C1;
--ELSE
------LEAVE loop_label;
--END IF;
END LOOP loop_label;
CLOSE C1;
END;

例3:使用WHILE循环
 

复制代码 代码示例:

CREATE PROCEDURE QGPL/TEST_WHILE
LANGUAGE SQL
BEGIN
DECLARE code_v char(10);
DECLARE salary_v integer;
DECLARE city_v char(20);
DECLARE at_end integer;

DECLARE C1 CURSOR FOR
---SELECT code,salary,city FROM employee WHERE city="Beijing";
OPEN C1;

SET at_end=0;
WHILE at_end = 0 DO
--FETCH C1 INTO code_v,salary_v,city_v;
--IF SQLCODE=0 THEN
------SET salary_v=salary_v*1.1;
------UPDATE employee SET salary=salary_v
---------WHERE CURRENT OF C1;
--ELSE
------SET at_end=1;
--END IF;
END WHILE;
CLOSE C1;
END;

例4:使用REPEAT循环
 

复制代码 代码示例:

CREATE PROCEDURE QGPL/TEST_REPEAT
LANGUAGE SQL
BEGIN
DECLARE code_v char(10);
DECLARE salary_v integer;
DECLARE city_v char(20);

DECLARE C1 CURSOR FOR
---SELECT code,salary,city FROM employee WHERE city="Beijing";
OPEN C1;

repeat_label:
REPEAT
--FETCH C1 INTO code_v,salary_v,city_v;
--IF SQLCODE=0 THEN
------SET salary_v=salary_v*1.1;
------UPDATE employee SET salary=salary_v
---------WHERE CURRENT OF C1;
--END IF;
--UNTIL SQLCODE<>0;
END REPEAT repeat_loop;
CLOSE C1;
END;