oracle 我想使用PL/SQL从tableA的列名rollnoofstud中提取列值

h5qlskok  于 2022-11-22  发布在  Oracle
关注(0)|答案(1)|浏览(128)
DECLARE
 TYPE norollno IS TABLE OF VARCHAR2(100);
      rollno norollno;
BEGIN
   BEGIN
      SELECT token
      BULK COLLECT INTO rollno
      FROM tableA
      WHERE columname='rollnoofstud';
   EXCEPTION
   WHEN NO_DATA_FOUND THEN
      rollno := norollno();
  END ;

  IF rollno >0 THEN
  FOR i IN rollno.FIRST..norollno.LAST
  LOOP
    <doSomeThing>
  END LOOP;
  END IF;
END;

我正在尝试此操作,但没有得到输出。我怀疑我的选择语句是否正确。

siv3szwd

siv3szwd1#

我没有你的表,所以我创建了一个:

SQL> CREATE TABLE tablea
  2  AS
  3     SELECT ename AS token, 'rollnoofstud' AS columname
  4       FROM emp
  5      WHERE deptno = 10;

Table created.

您发布的代码并没有错;需要一点修正(参见第17行,检查集合是否包含某些内容的方法(count it!); FOR循环中的排印错误):

SQL> SET SERVEROUTPUT ON
SQL> DECLARE
  2     TYPE norollno IS TABLE OF VARCHAR2 (100);
  3
  4     rollno  norollno;
  5  BEGIN
  6     BEGIN
  7        SELECT token
  8          BULK COLLECT INTO rollno
  9          FROM tableA
 10         WHERE columname = 'rollnoofstud';
 11     EXCEPTION
 12        WHEN NO_DATA_FOUND
 13        THEN
 14           rollno := norollno ();
 15     END;
 16
 17     IF rollno.COUNT > 0
 18     THEN
 19        FOR i IN rollno.FIRST .. rollno.LAST
 20        LOOP
 21           DBMS_OUTPUT.put_line (rollno (i));
 22        END LOOP;
 23     END IF;
 24  END;
 25  /
CLARK                    --> here's the result
KING
MILLER

PL/SQL procedure successfully completed.

SQL>

[EDIT:使用示例表与数据:]

(note Oracle中没有text数据类型!)

SQL> CREATE TABLE students
  2  (
  3     rollnostud   INTEGER PRIMARY KEY,
  4     name         VARCHAR2 (10) NOT NULL,
  5     gender       VARCHAR2 (1) NOT NULL
  6  );

Table created.

SQL> INSERT INTO students
  2       VALUES (1, 'Ryan', 'M');

1 row created.

SQL> INSERT INTO students
  2       VALUES (2, 'Joanna', 'F');

1 row created.

SQL> INSERT INTO students
  2       VALUES (3, 'John', 'M');

1 row created.

程序:

SQL> SET SERVEROUTPUT ON
SQL>
SQL> DECLARE
  2     TYPE norollno IS TABLE OF VARCHAR2 (100);
  3
  4     rollno  norollno;
  5  BEGIN
  6     BEGIN
  7        SELECT name
  8          BULK COLLECT INTO rollno
  9          FROM students;
 10     EXCEPTION
 11        WHEN NO_DATA_FOUND
 12        THEN
 13           rollno := norollno ();
 14     END;
 15
 16     IF rollno.COUNT > 0
 17     THEN
 18        FOR i IN rollno.FIRST .. rollno.LAST
 19        LOOP
 20           DBMS_OUTPUT.put_line (rollno (i));
 21        END LOOP;
 22     END IF;
 23  END;
 24  /
Ryan
Joanna
John

PL/SQL procedure successfully completed.

SQL>

相关问题