I Have to create a table currencies
CREATE TABLE currencies (
from_currency CHAR(30) NOT NULL,
ExchRate REAL NOT NULL,
to_currency CHAR(30) NOT NULL,
PRIMARY KEY (from_currency),
FOREIGN KEY (to_currency) REFERENCES currencies(from_currency)
)
I have to save exchange rate for 6 currencies: (inr,eur,cad,usd,gbp,cfp) But the problem is i can't store same values in first column ie I can save my currency rate as follow
from_curr ER --> to_curr
INR --> 60 --> USD
USD --> 0 --> USD
GBP --> 70 --> USD
etc for all the currencies but now the problem is while i try to store the currency for other er like
INR --> 1 --> USD
or
GBP --> 70 --> USD
I get error duplicates values are not allowed ? How to solvve this problem ?
You are not storing a currency, but rather a pair of currencies.
CREATE TABLE currency_exchange_rates (
from_currency CHAR(30) NOT NULL,
to_currency CHAR(30) NOT NULL,
ExchRate REAL NOT NULL,
PRIMARY KEY (from_currency,to_currency),
)
I would also suggest a separate table holding the six currencies and linking the table above to ensure valid currency codes. You might also want to hold a date field (and make it part of the primary key), since rates can change over time...
You should either create a composite primary key as a pair of 2 currencies is uniquely identifying a record for you.
CREATE TABLE currencies (
from_currency CHAR(30) NOT NULL,
ExchRate REAL NOT NULL,
to_currency CHAR(30) NOT NULL,
PRIMARY KEY (from_currency, to_currency)
)
Or alternatively you can add a new column for the primary key, eg as autoincrement column:
CREATE TABLE currencies (
[Id] [int] IDENTITY(1,1) NOT NULL
from_currency CHAR(30) NOT NULL,
ExchRate REAL NOT NULL,
to_currency CHAR(30) NOT NULL,
PRIMARY KEY ([Id])
)
Of course you can't. That's because you defined PRIMARY KEY ()
. Thus only distinct value is allowed for this column. What you need instead is that pairs of from_currency/to_currency are unique. You can do this by defining a composite PK in your table:
CREATE TABLE currencies (
from_currency CHAR(30) NOT NULL,
ExchRate REAL NOT NULL,
to_currency CHAR(30) NOT NULL,
PRIMARY KEY (from_currency, to_currency)
)
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.