1

如何将此代码转换为具有相同输出的函数?

declare
  record_name employees%ROWTYPE; 
begin
  FOR record_name IN (SELECT (a.first_name || ' ' || a.last_name) complete_name,
                      b.DEPARTMENT_NAME complete_name2
                     FROM employees a , departments b
                     WHERE ROWNUM < 1000 and a.DEPARTMENT_ID=b.DEPARTMENT_ID)
  LOOP 
    DBMS_OUTPUT.PUT_LINE('Employee name: ' || record_name.complete_name 
                           ||'DEPARTMENT name: '||record_name.complete_name2);
  END LOOP;
END;
4

2 回答 2

0
create or replace function SOME_FUNCTION
RETURN VARCHAR
AS
  record_name employees%ROWTYPE;
  out_stmt varchar(4000); 
  TOO_LONG EXCEPTION;
BEGIN
  FOR record_name IN (SELECT (a.first_name || ' ' || a.last_name) complete_name,
                      b.DEPARTMENT_NAME complete_name2
                     FROM employees a , departments b
                     WHERE ROWNUM < 1000 and a.DEPARTMENT_ID=b.DEPARTMENT_ID)
  LOOP
    IF (LENGTH(out_stmt) < 4000) THEN
       out_stmt := out_stmt || 'Employee name: ' || record_name.complete_name || 'DEPARTMENT name: '||record_name.complete_name2;
    ELSE
       RAISE TOO_LONG;
    END IF;
  END LOOP;
  return out_stmt;
EXCEPTION
   WHEN TOO_LONG THEN
      RETURN 'OVERFLOW';
END;

快速示例,我不知道是否某些类型没有完整性限制,因为并不总是varchar(4000)足够。但我听说过这种类型的东西,但现在我不知道是否存在。

当您在应用层使用它时,必须以某种方式格式化返回的字符串。

于 2012-05-31T22:18:05.297 回答
0
CREATE TYPE some_employees_record IS RECORD
  (emp_name VARCHAR2(4000)
  ,dept_name VARCHAR2(4000));
CREATE TYPE employees_tab_type IS TABLE OF some_employees_record;

CREATE OR REPLACE
FUNCTION some_employees
RETURN employees_tab_type
PIPELINED
IS
  rec some_employees_record; 
BEGIN
  FOR record_name IN (SELECT (a.first_name || ' ' || a.last_name) complete_name,
                      b.DEPARTMENT_NAME complete_name2
                     FROM employees a , departments b
                     WHERE ROWNUM < 1000 and a.DEPARTMENT_ID=b.DEPARTMENT_ID)
  LOOP
    rec.emp_name := record_name.complete_name;
    rec.dept_name := record_name.complete_name2;
    PIPE ROW (rec);
  END LOOP;
  RETURN;
END;

您可以通过两种方式调用上述函数。在 SQL 中:

SELECT * FROM TABLE(some_employees);

或在 PL/SQL 中:

DECLARE
  rt employees_tab_type;
BEGIN
  rt := some_employees;
  FOR i IN 1..rt.COUNT LOOP
    DBMS_OUTPUT.put_line(rt(i).emp_name || ', ' || rt(i).dept_name);
  END LOOP;
END;

OT:如果记录数超过 999,您是否意识到查询返回有效随机(非确定性)的 999 条记录集?

顺便说一句,这只是为了示例目的。如果您唯一的要求是运行查询的函数,我不会这样做。我会返回一个引用游标,或者(甚至更好)将查询放在视图中。

于 2012-06-01T01:07:10.260 回答