简体   繁体   中英

How to reference foreign key of another schema table while creating table?

I have two Schemas :-

  • GamersProfileDB - Contain UserCredential_tbl table
  • DeveloperDB - Contain PlayerAchievements_tbl table

Now while creating table called PlayerAchievements_tbl , i want to reference it from another schema table Usercredential_tbl . Here is the following sql query :-

create table PlayerAchievements_tbl 
(
pid number(10) references gamersprofiledb.usercredential (id),
aid number(10) references achievements (id) 
);

But the above query gave me 'table or view does not exist' error

This (possible duplicate) answer adding foreign_key in ALTER operation whereas i want it to add foreign_key on CREATE TABLE operation and Moreover it also didn't specify what grants or privileges may require to execute this query

So my exact question would be :-

1) could it be possible to reference another schema table into existing schema table while creating new table ?

2) or do we need some privileges to execute this query ?

Thanks in Advance.

By default an (unprivileged) user has no permissions to see objects owned by another user. You need to GRANT the privilege using:

GRANT REFERENCES ON GamersProfileDB.UserCredential TO DeveloperDB;

or, if you also need to SELECT from the table then:

GRANT SELECT ON GamersProfileDB.UserCredential TO DeveloperDB;

Once you have permissions to reference (or select) the table then you can use:

CREATE TABLE PlayerAchievements_tbl                  -- Why add the "_tbl" suffix?
(
  pid number(10)
      CONSTRAINT PlayerAchievements__PID__FK         -- name the constraint
        REFERENCES GamersProfileDB.UserCredential (id),
  aid number(10)
      CONSTRAINT PlayerAchievements__AID__FK         -- name the constraint
        REFERENCES Achievements (id),
  CONSTRAINT PlayerAchievements__PID_AID__PK
    PRIMARY KEY ( pid, aid )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM