问题
I'm creating a table in Oracle 11g like this:
CREATE TABLE EXAMPLE (
ID VARCHAR2(10) PRIMARY KEY,
NAME VARCHAR2(100),
SHORT VARCHAR2(50),
CURRENCY CHAR(3)
);
Is it possible to create a foreign key constraint or even a check constraint on CURRENCY to a built-in Oracle table that contains the ISO currencies?
Not having a great understanding of databases I also take as input other solutions that might be out there, however I do not want to maintain my own table for this, if it's too much work, I'll live with user errors.
Thanks.
回答1:
Note: Edited to include @A.B.Cade's suggestion.
Unfortunately you can't directly add a constraint, as the currencies data is available through a system a view. You can, however, create your own table with that information and then create the foreign key. Here's an example of how you can do it.
CREATE TABLE currencies (
country VARCHAR2(30) PRIMARY KEY,
currency VARCHAR2(3) NOT NULL
);
INSERT INTO currencies
SELECT value country, utl_i18n.get_default_iso_currency(value) currency
FROM v$nls_valid_values
WHERE parameter = 'TERRITORY';
CREATE INDEX currencies_iso_idx ON currencies(currency) COMPUTE STATISTICS;
ALTER TABLE example ADD CONSTRAINT example_currency_fk FOREIGN KEY (currency)
REFERENCES currencies(currency);
The example above includes an index on the currency value, as I suspect that will what you'll be querying on.
回答2:
You can get a list of ISO currencies from a built in view in oracle:
select utl_i18n.GET_DEFAULT_ISO_CURRENCY(value) iso_cur
from v$nls_valid_values
where parameter = 'TERRITORY'
But as Nuno Guerreiro said, you'll need to create a table from these results and add a foreign key to the new table.
回答3:
Actually I don't understand what do you mean by "default Oracle table that contains ISO currencies" (do you mean Oracle PeopleSoft CURRENCY_CD_TBL table?), but in general you can alter your table after creation to add foreign key constraint. Here is an example:
ALTER TABLE EXAMPLE
ADD CONSTRAINT fk_currency
FOREIGN KEY (CURRENCY)
REFERENCES put_parent_table_name_here(_corresponding_field_name_in_perent_table);
You also can add constraint definition into CREATE TABLE statement. Here is an example:
CREATE TABLE EXAMPLE (
ID VARCHAR2(10) PRIMARY KEY,
NAME VARCHAR2(100),
SHORT VARCHAR2(50),
CURRENCY CHAR(3),
CONSTRAINT fk_currency
FOREIGN KEY (CURRENCY)
REFERENCES put_parent_table_name_here(_corresponding_field_name_in_perent_table)
);
来源:https://stackoverflow.com/questions/22808897/does-oracle-provide-a-built-in-currency-table-for-me-to-use-as-constraints