To run PL/SQL scripts or execute SQL commands directly from the terminal, you use Oracle’s Secure External Table (SET) or the SQL*Plus command-line tool. This achieves precise, automated database operations without GUI tools, ideal for scripted batch jobs, testing, or troubleshooting. You’ll need Oracle Database installed and the necessary client software, but no additional tools beyond a text editor or IDE are required.

What You'll Need

  • An Oracle Database installation (10g or later) with SQL*Plus enabled.
  • Oracle client tools installed (including SQL*Plus) to connect to your database.
  • A text editor or IDE (e.g., Notepad++, VS Code) to write PL/SQL scripts.
  • Oracle SID or TNS entry details (host, port, service name) for secure connection.
  • Privileges to execute SQL/PL/SQL statements (typically via a user with DBA or sufficient permissions).

Step-by-Step

  1. Open SQL*Plus Terminal

    Launch SQL*Plus from your terminal or command prompt. Use one of these methods:

    • For Linux/macOS: Navigate to your Oracle installation directory and run: sqlplus username/password@database (e.g., sqlplus sys/password@ORCL for a sysdba connection).
    • For Windows: Use the Oracle home directory (e.g., `C:\app\oracle\product\11.2.0\db_1\bin\sqlplus.exe`) and enter the same command.
    • If prompted, enter the password for the specified username.

    If you’re using a TNS entry (e.g., for remote databases), replace the database argument with: @tns_entry_name (e.g., @ORCL).

  2. Connect to the Database

    Verify your connection by typing: SQL> SHOW USER

    • If you’re not already connected as a privileged user, switch to one with DBA rights: SQL> CONNECT sys/password@database AS SYSDBA (Replace with your actual SYSDBA credentials if using Oracle 11g+).
    • If you lack DBA privileges, use a non-privileged account with sufficient permissions (e.g., CONNECT myuser/mypassword@database).

    Exit SQL*Plus with EXIT when done.

  3. Write and Execute a PL/SQL Script

    Create a script (e.g., script.sql) in a text editor. Example:

        BEGIN
          DBMS_OUTPUT.PUT_LINE('Hello from PL/SQL!');
          INSERT INTO employees (id, name) VALUES (101, 'John Doe');
        END;
        /
        

    The trailing slash (/) marks the end of the script. Run it with: SQL> @script.sql

    For direct execution without saving: SQL> BEGIN > DBMS_OUTPUT.PUT_LINE('Test'); > END; > /

  4. Use External Tables for Large Scripts

    To run scripts from the command line without saving them, use Oracle’s Secure External Table (SET):

        SET LONG 1000000
        SET LONGCHARS ON
        SET LINESIZE 120
    
        -- Define the external table path
        CREATE OR REPLACE DIRECTORY mydir AS '/path/to/scripts';
        GRANT READ ON DIRECTORY mydir TO public;
    
        -- Connect to the external table
        SQL> @/mydir/my_script.sql
        

    Replace /path/to/scripts with an absolute directory path where your scripts reside. Ensure the directory exists and the Oracle user has read permissions.

  5. Handle Errors Gracefully

    Use SET SERVEROUTPUT ON SIZE 1000000 to view PL/SQL output:

        SQL> SET SERVEROUTPUT ON SIZE 1000000
        SQL> BEGIN
        >   -- Your PL/SQL code here
        > END;
        > /
        

    For debugging, enable trace logs: SQL> SET LINESIZE 200 and SQL> SET PAGESIZE 0 to suppress page breaks.

Common Mistakes

  • Missing Slash (/): Forgetting the script terminator causes SQL*Plus to wait for input indefinitely. Always include / at the end of scripts.
  • Incorrect Credentials: Using the wrong username/password or SID fails authentication. Double-check the connection syntax: username/password@database or @tns_entry.
  • Directory Permissions: SET scripts require the Oracle user to have read access to the script directory. Use GRANT READ ON DIRECTORY dblink TO username if needed.
  • Syntax Errors: Typos in PL/SQL (e.g., missing semicolons) or SQL (e.g., column mismatches) trigger errors. Always test in SQL*Plus first.
  • Default Schema Issues: Running scripts without specifying a schema (e.g., @script.sql vs. @script.sql@SCHEMA) fails if objects belong to another user.

Tips

  • Use Variables for Reusability: Dynamically pass values with variables:
          SQL> VAR v_name VARCHAR2(50)
          SQL> BEGIN
          >   v_name := 'Alice';
          >   INSERT INTO users (name) VALUES (v_name);
          > END;
          /
  • Automate with Cron Jobs: Schedule PL/SQL scripts to run periodically via cron (Linux/Windows Task Scheduler). Example:
          0 3 * * * /usr/bin/sqlplus -S username/password@database @/path/to/script.sql
  • Export Results to Files: Use WRITE STDOUT to log output:
          BEGIN
            DBMS_OUTPUT.WRITE_LINE('Data processed');
          END;
          /
          SET HEADING OFF
          SET FEEDBACK OFF
          SELECT * FROM table_name WHERE condition;
          
  • Batch Processing: Combine SQL and PL/SQL for complex workflows:
          BEGIN
            EXECUTE IMMEDIATE 'DELETE FROM temp_table';
            INSERT INTO table1 SELECT * FROM table2 WHERE condition;
          END;
          /
  • Use SQLcl for Modern Workflows: Oracle’s sqlcl (SQL Client) supports JSON/YAML scripts and better IDE integration than SQL*Plus.

Troubleshooting

If commands fail, start with these diagnostics:

  1. Check Connection: Verify the Oracle service is running: sqlplus -S username/password@database && sqlplus -V (Use sqlplus -V to confirm SQL*Plus is in PATH on Windows).
  2. Test Basic Queries: Run a simple query to isolate issues: SQL> SELECT 1 FROM dual; If this fails, the connection is broken.
  3. Inspect Scripts: Open the script file in a text editor to ensure no hidden characters or encoding issues.
  4. Review Logs: Check Oracle error logs (typically in $ORACLE_BASE/diag/rdbms/) for detailed errors.

If SET Scripts Fail: Verify the directory exists and the Oracle user has read permissions: SQL> SHOW DIRECTORY mydir If missing, create it: CREATE DIRECTORY mydir AS '/path/to'; GRANT READ ON DIRECTORY mydir TO public;

Frequently Asked Questions

1. Can I run PL/SQL scripts directly from the command line?

Yes, via SQL*Plus or Secure External Tables (SET). The command @script.sql executes a saved script without GUI prompts.

2. What if SQL*Plus isn’t installed?

Install Oracle client software (includes SQL*Plus) from the Oracle database installation media. For Linux/macOS, run: sudo apt-get install oracle-client (Debian/Ubuntu) or: brew install oracle-instantclient (Homebrew).

3. How do I debug PL/SQL errors?

Enable server output and use BEGIN ... EXCEPTION blocks to catch errors:

  SQL> SET SERVEROUTPUT ON
  SQL> BEGIN
  >   -- Your code
  >   EXCEPTION
  >     WHEN OTHERS THEN
  >       DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
  > END;
  /

4. Can I use PL/SQL from a non-privileged account?

Yes, but with limitations. Non-privileged users can execute scripts if they have permissions to run the objects (e.g., CREATE SESSION for DML). Use CONNECT myuser/mypassword@database.

5. How do I export PL/SQL results to a file?

Redirect output to a file: SQL> @script.sql > output.log Or use WRITE STDOUT in PL/SQL:

  BEGIN
    DBMS_OUTPUT.WRITE_LINE('Data: ' || TO_CHAR(SYSDATE));
  END;
  /

6. What’s the difference between SQL*Plus and sqlcl?

sqlcl (Oracle’s modern client) supports JSON/YAML scripts, better error handling, and integration with IDEs like IntelliJ or VS Code. SQL*Plus is legacy but remains widely used for scripting.

For scripts larger than 1MB, consider using Oracle’s Data Pump (expdp/impdp) instead of SQL*Plus.