Thursday, May 19, 2011

PL/SQL proc to add a column to a table if it does not exist

create or replace function ddl_column_exists(p_table     in varchar2,
                                             p_fieldname in varchar2) return number is
  
  result number;

begin
  select count(*)
    into result
    from user_tab_columns c
   where lower(c.COLUMN_NAME) = lower(p_fieldname)
     and lower(c.TABLE_NAME) = lower(p_table);

  if result >0 then
    result := 1;
  else
    result := 0;
  end if;

  return(result);
end;
/
CREATE OR REPLACE PROCEDURE "DDL_USP_ADDCOL" (p_tblName varchar2,
                                              p_fldName varchar2,
                                              p_dtype   varchar2) iS
    v_ret number(2) := 0;
    v_sql varchar2(2000);
begin

    select count(*)
      into v_ret
      from user_tab_columns c
     where lower(c.COLUMN_NAME) = lower(p_fldName)
       and lower(c.TABLE_NAME) = lower(p_tblName);

    if v_ret = 0 then

        --print 'adding field'
        v_sql := 'ALTER TABLE ' || p_tblName || ' add ' || p_fldName || ' ' || p_dtype;
        execute immediate v_sql;

    end if;
end;