2012-05-31 94 views
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; 
+0

你只想打印還是希望函數返回記錄集以便進一步操作?對於前者,請使用@Sajmon給出的答案,用Put_Line替換累積級聯。對於後者,您需要創建一個表值函數。 – SQLCurious

回答

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)足夠多。但我聽說過這種類型的東西,但現在我不知道它是否存在。

當你將在應用層使用它時,必須以某種方式格式化返回的字符串。

+0

從Oracle 10g開始,max varchar是4000.而且,你不覺得'+'符號贏了嗎?爲連接起作用? [out_stmt:= out_stmt +'員工姓名:'] - 應該是|| – codingbiz

+0

哦,我的傻瓜,謝謝,所以T-SQL對我有不好的影響.. – Sajmon

+0

可能還想在那裏有一個異常處理程序,以防你溢出你的out_stmt變量。 – DCookie

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 ?

順便說一句,這只是爲了舉例的目的。如果你唯一的要求是一個函數運行查詢,我不會這樣做。我會返回一個遊標,或者(甚至更好)將查詢放在視圖中。