oracle-databasestored-proceduresdatabase-link

Creating a DB link if not created inside a stored procedure


I'm trying to code a stored procedure in Oracle. I don't have a ton of experience with it and I'm running to an issue. The end goal of the procedure is to take data from one DB and put it into another in a different form. I have most of the procedure working it seems but I'm having issues with something that seems like it should be simple. At the beginning of the code, I would like to check to make sure a DB link is created. If not, then I want to create the db link.

This is what I put inside my procedure:

IF (select count(1) from ALL_DB_LINKS where db_link = 'DB_LINK.NAME.COM') = 0 THEN
      CREATE DATABASE LINK LINK_NAME
      CONNECT TO username IDENTIFIED BY password
      USING 'SID';
END IF;

I know the link works because I've done it outside this and did a lookup with it. The error I get when I try to compile is this:

Encountered the symbol "CREATE" when expecting one of the following:

I've done all the googling I think I can do and I cannot figure out what I am doing wrong. To head off the other question I have, I've also tried to do it by putting in:

DECLARE test_count number;

select count(1) into test_count from ALL_DB_LINKS where db_link = 'DB_LINK.NAME.COM';
 BEGIN
  IF test_count = 0 THEN
      CREATE DATABASE LINK LINK_NAME
      CONNECT TO username IDENTIFIED BY password
      USING 'SID';
  END IF;
END;

But I get the same error. I'm also not sure if having a begin inside a begin will work. Any help would be a great... well, help.


Solution

  • Oracle compiles packages and in order to do that all objects referenced in code need to already exist. This includes objects referenced over a database link. Things will get marked invalid if the referenced objects don't exist. Usually a DBA will create and maintain such an environment using PL/SQL scripts and not stored procedures.

    If you really want to anyway:

    EXECUTE IMMEDIATE q'[ CREATE DATABASE LINK LINK_NAME
          CONNECT TO username IDENTIFIED BY password
          USING 'SID']';