Two practical ORACLE procedures for adding/dropping fields

DECLARE
    -- Procedure to add a column if it does not exist
    PROCEDURE add_column_if_not_exists (
        p_owner       VARCHAR2,
        p_table_name  VARCHAR2,
        p_column_name VARCHAR2,
        p_column_type VARCHAR2
    ) IS
        l_sql    VARCHAR2(1024);
        l_count  NUMBER;
    BEGIN
        -- Check if column exists
        SELECT COUNT(*)
        INTO l_count
        FROM ALL_TAB_COLUMNS
        WHERE OWNER = p_owner
          AND TABLE_NAME = p_table_name
          AND COLUMN_NAME = p_column_name;

        -- Add column if it does not exist
        IF l_count = 0 THEN
            l_sql := 'ALTER TABLE ' || p_owner || '.' || p_table_name || ' ADD (' || p_column_name || ' ' || p_column_type || ')';
            DBMS_OUTPUT.PUT_LINE(l_sql);
            EXECUTE IMMEDIATE l_sql;
        END IF;
    END;

    -- Procedure to drop a column if it does exist
    PROCEDURE drop_column_if_exists (
        p_owner       VARCHAR2,
        p_table_name  VARCHAR2,
        p_column_name VARCHAR2
    ) IS
        l_sql    VARCHAR2(1024);
        l_count  NUMBER;
    BEGIN
        -- Check if column exists
        SELECT COUNT(*)
        INTO l_count
        FROM ALL_TAB_COLUMNS
        WHERE OWNER = p_owner
          AND TABLE_NAME = p_table_name
          AND COLUMN_NAME = p_column_name;

        -- drop column if it does exist
        IF l_count = 1 THEN
            l_sql := 'ALTER TABLE ' || p_owner || '.' || p_table_name || ' DROP COLUMN ' || p_column_name;
            DBMS_OUTPUT.PUT_LINE(l_sql);
            EXECUTE IMMEDIATE l_sql;
        END IF;
    END;
BEGIN
...
END;
/

Comments

  1. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.