查看列是否存在的函数

时间:2019-07-25 04:44:30

标签: oracle plsql

我在检查表中是否存在列的功能时遇到了问题

试图查看v_col是否在数据库表all_tab_cols中有效列

create or replace function exist(v_col in varchar2) 
 Return integer is
 Res integer:= 0;
 Begin
 v_sql := 'SELECT ' ||
  'COLUMN_NAME ' ||
  'FROM ' ||
  ' all_tab_cols ' ||
  'WHERE ' ||
  'COLUMN_NAME = ''|| v_col||''';
Begin
Execute immediate v_sql;   
Res:=1;
Exception when other then null;
End;
Return (Res);
End;
BEGIN
DBMS_OUTPUT.PUT_LINE(exist('ORDER_NUMBER' )); 
END;
/

1 个答案:

答案 0 :(得分:2)

不需要动态SQL

CREATE OR REPLACE FUNCTION exist (
     v_col IN VARCHAR2
) 
 RETURN integer is
 res integer;
 BEGIN

 select 1 INTO res from all_tab_cols where 
    column_name = v_col and rownum = 1; --can have >1 columns with same name
 return res;
EXCEPTION when no_data_found THEN
          res := 0;
RETURN res;
END;
/