Oracle PLSQL

1、SELECT INTO语句:用于把从数据库查询出内容存入变量

  1. DECLARE
  2. v_hire_date employees.hire_date%TYPE;
  3. v_salary employees.salary%TYPE;
  4. BEGIN
  5. SELECT hire_date, salary
  6. INTO v_hire_date, v_salary
  7. FROM employees
  8. WHERE employee_id = 100;
  9. ...
  10. END;
  11. /
  12. SET SERVEROUTPUT ON
  13. DECLARE
  14. v_sum_sal NUMBER(10,2);
  15. v_deptno NUMBER NOT NULL := 60;
  16. BEGIN
  17. SELECT SUM(salary) -- group function
  18. INTO v_sum_sal
  19. FROM employees
  20. WHERE department_id = v_deptno;
  21. DBMS_OUTPUT.PUT_LINE ('The sum salary is ' ||
  22. TO_CHAR(v_sum_sal));
  23. END;
  24. /

2、PLSQL中的控制语句

A.判断语句

  1. IF condition THEN
  2. statements;
  3. [ELSIF condition THEN
  4. statements;]
  5. [ELSE
  6. statements;]
  7. END IF;
  1. CASE selector
  2. WHEN expression1 THEN result1
  3. WHEN expression2 THEN result2
  4. ...
  5. WHEN expressionN THEN resultN
  6. [ELSE resultN+1;]
  7. END;

1,对NULL的判断处理

B.循环语句

1,基本循环

  1. LOOP
  2. statement1;
  3. . . .
  4. EXIT [WHEN condition];
  5. END LOOP;

2,For循环

  1. FOR counter IN [REVERSE]
  2. lower_bound..upper_bound LOOP
  3. statement1;
  4. statement2;
  5. . . .
  6. END LOOP;
  1. DECLARE
  2. v_country_id locations.country_id%TYPE := 'CA';
  3. v_location_id locations.location_id%TYPE;
  4. v_city locations.city%TYPE := 'Montreal';
  5. BEGIN
  6. SELECT MAX(location_id) INTO v_location_id
  7. FROM locations
  8. WHERE country_id = v_country_id;
  9. FOR i IN 1..3 LOOP
  10. INSERT INTO locations(location_id, city, country_id)
  11. VALUES((v_location_id + i), v_city, v_country_id );
  12. END LOOP;
  13. END;
  14. /

3,Wihle循环

  1. WHILE condition LOOP
  2. statement1;
  3. statement2;
  4. . . .
  5. END LOOP;

4,嵌套循环和Label

Label一般用不着,只有在使用goto语句,或者内部循环需要访问外部的同名变量的时候才需要,而一般这 种做法也是不被提倡的

  1. ...
  2. BEGIN
  3. <<Outer_loop>>
  4. LOOP
  5. v_counter := v_counter+1;
  6. EXIT WHEN v_counter>10;
  7. <<Inner_loop>>
  8. LOOP
  9. ...
  10. EXIT Outer_loop WHEN total_done = 'YES';
  11. -- Leave both loops
  12. EXIT WHEN inner_done = 'YES';
  13. -- Leave inner loop only
  14. ...
  15. END LOOP Inner_loop;
  16. ...
  17. END LOOP Outer_loop;
  18. END;