Cursor –[游标]:
Step1——Example table 1×2
CREATE TABLE product_types (
product_type_id INTEGER
CONSTRAINT product_types_pk PRIMARY KEY,
name VARCHAR2(10) NOT NULL
);
/
CREATE TABLE products (
product_id INTEGER
CONSTRAINT products_pk PRIMARY KEY,
product_type_id INTEGER
CONSTRAINT products_fk_product_types
REFERENCES product_types(product_type_id),
name VARCHAR2(30) NOT NULL,
description VARCHAR2(50),
price NUMBER(5, 2)
);
/
SET SERVEROUTPUT ON
Step2——Example cursor1×1
DECLARE
-- step 1: declare the variables [step1.声明变量]
v_product_id products.product_id%TYPE;
v_name products.name%TYPE;
v_price products.price%TYPE;
-- step 2: declare the cursor [step2.声明游标]
CURSOR cv_product_cursor IS
SELECT product_id, name, price
FROM products
ORDER BY product_id;
BEGIN
-- step 3: open the cursor [step3.打开游标]
OPEN cv_product_cursor;
LOOP
-- step 4: fetch the rows from the cursor [step4.游标,遍历行]
FETCH cv_product_cursor
INTO v_product_id, v_name, v_price;
-- exit the loop when there are no more rows, as indicated by
-- the Boolean variable cv_product_cursor%NOTFOUND (= true when
-- there are no more rows)
EXIT WHEN cv_product_cursor%NOTFOUND;
-- use DBMS_OUTPUT.PUT_LINE() to display the variables
DBMS_OUTPUT.PUT_LINE(
'v_product_id = ' || v_product_id || ', v_name = ' || v_name ||
', v_price = ' || v_price
);
END LOOP;
-- step 5: close the cursor [step5.关闭游标]
CLOSE cv_product_cursor;
END;
/