2013-04-16 50 views
0

我已将单个行提取到rowType变量中。这一行有80列。所以,我不想 想要在我的程序中硬编码列名并从数据字典中获取列名。在StoredProcedure中获取一行中的所有列到集合中

请有人告诉我,我怎么能访问indivisual列值????? 以下是我的代码。

DECLARE 
fetchedRow EMP%ROWTYPE; 
TYPE columnNameList IS TABLE OF USER_TAB_COLUMNS.column_name%TYPE; 
CURSOR empCursor IS select column_name from USER_TAB_COLUMNS where table_name = 'EMP'; 
empColumnNames columnNameList; 
colName varchar2(100); 
BEGIN 
    -- Fetching column names of EMP from data dictionary 
    OPEN empCursor; 
    FETCH empCursor BULK COLLECT INTO empColumnNames; 
    CLOSE empCursor; 
    DBMS_OUTPUT.PUT_LINE('Columns fetched'); 

BEGIN 
    SELECT * into fetchedRow from EMP where EMP_ID = 1234; 
END; 

colName := 'fetchedRow.'||empColumnNames(1); --- colName will have fetchedRow.EMP_ID 
DBMS_OUTPUT.PUT_LINE('Going to Compare'||colName); 

--stuck here 
    if colName = 1234 then -- Want to compare value of fetchedRow.EMP_ID with 1234 
     DBMS_OUTPUT.PUT_LINE('Matching'); 
    else 
    DBMS_OUTPUT.PUT_LINE('Not-Matching'); 
    END IF; 
EXCEPTION 
    WHEN OTHERS THEN 
     DBMS_OUTPUT.PUT_LINE('Error'||SQLERRM); 

END; 

回答

0

您需要使用动态SQL以这种方式访问​​字段,但一个小窍门是将当前行放置到可从SQL语句访问的某个位置,例如包头。

汤姆凯特一如既往,看看here

带有现场示例的SQL小提箱可以找到here

用于说明某些代码:

申报包报头

create or replace package TmpRowAccess as 

    CurRow emp%rowtype; 

end; 

当读取行 - 它读取到包变量

SELECT * into TmpRowAccess.CurRow from EMP where rownum = 1; 

构建访问字段值

declare 
    vRes char(1); 
    vParam number := 1234; 
    begin 

    execute immediate 
     ' 
     begin 
      if(:1 = TmpRowAccess.CurRow.'|| colName ||') then 
      :2 := ''Y''; 
      else 
      :2 := ''N''; 
      end if; 
     end; 
     ' 
     using in vParam, out vRes; 

    if(vRes = 'Y') then 
     DBMS_OUTPUT.PUT_LINE('Matching'); 
    else 
     DBMS_OUTPUT.PUT_LINE('Not-Matching'); 
    end if; 

    end; 
相关问题