Get foreign key between two dates - sql

It is necessary to analyze the fluctuations in exchange rates, depending on the sign of the zodiac.
I would like to insert foreign key (zodiak_id) in the follow table:
create table CURRENCY (
CUR_ID number NOT NULL,
CUR_DATE DATE not null,
CUR_NAME varchar2(3) not null,
VALUE NUMBER not null,
Zodiac_id number,
constraint PK_CUR primary key (CUR_ID),
CONSTRAINT FK_ZOD FOREIGN KEY (Zodiac_id) REFERENCES Zodiac(Zodiac_id)
);
of this table:
create table Zodiac (
Zodiac_id number not null,
Zodiac_name VARCHAR2(15) not null,
START_PERIOD date,
END_PERIOD date,
constraint PK_Zod primary key (Zodiac_id)
);
The sqls i wrote is below:
insert into CURRENCY cr(Zodiac_id)
select Zodiac_id from ZODIAC z
where cr.CUR_DATE >= z.START_PERIOD and cr.CUR_DATE <= z.END_PERIOD;
But get this error: SQL Error: ORA-00904: "CR"."CUR_DATE": invalid identifier
Thanks in advance for your help.

Try this;
insert into CURRENCY (Zodiac_id)
select Z.Zodiac_id from Zodiac Z
inner join CURRENCY CR ON CR.Zodiac_id=Z.Zodiac_id
WHERE CR.CUR_DATE BETWEEN Z.START_PERIOD AND Z.END_PERIOD

It's because you're inserting only the zodiac_id into the CURRENCY table, but cur_date is a required field. You've marked it with a "not null" constraint in the create table statement.

Related

"no matching unique or primary key for this column-list" Error in SQL

Was creating some tables in SQL and got stuck when I had to design the following tables:
As you can see it is impossible to create Room details and services details Table without customer receipt table as they contain Receipt_no as the primary key.
Similarly, it is impossible to create a Customer Receipt table without Room_charges and Service_charges attributes without first creating the two details tables.
Hence, I first created a customer receipt table but without FK constraints on Room_Charges and Service_charges and then I created Services Details and Room Details tables.
Later, using ALTER command I tried to add FK Constraints on Customer Receipt table but it gives me this error
ORA-02270: no matching unique or primary key for this column-list
Now, after researching a bit about it on StackOverflow, there might be three possible cases as mentioned in the approved answer (# Oracle (ORA-02270) : no matching unique or primary key for this column-list error )
I think my case is number 3 as I have ensured the first two cases to be implemented.
Can anyone help me resolve it?
I am attaching SQL Code as a reference:
CREATE TABLE Customer_Receipt
(
Receipt_no VARCHAR2(12) PRIMARY KEY,
Booking_no NUMBER NOT NULL,
Total_charges NUMBER(12,2),
CONSTRAINT bookingnocustrec
FOREIGN KEY(Booking_no) REFERENCES Room_booking (Booking_no)
);
CREATE TABLE Services_Details
(
Receipt_no VARCHAR2(12) NOT NULL,
Service_offered VARCHAR2(8) NOT NULL,
Service_charges NUMBER(12,2),
PRIMARY KEY(Receipt_no, Service_offered),
CONSTRAINT recno
FOREIGN KEY(Receipt_no) REFERENCES Customer_receipt (Receipt_no)
);
ALTER TABLE Services_Details
MODIFY Service_charges NOT NULL;
CREATE TABLE Room_Details
(
Receipt_no VARCHAR2(12) NOT NULL,
Category_name VARCHAR2(9) NOT NULL,
Days_stayed INT,
Room_charges NUMBER(12,2),
PRIMARY KEY(Receipt_no, Category_name),
CONSTRAINT recno1
FOREIGN KEY(Receipt_no) REFERENCES Customer_receipt (Receipt_no),
CONSTRAINT catname1
FOREIGN KEY(Category_name) REFERENCES Room_category (Category_name)
);
ALTER TABLE Customer_receipt
ADD Room_charges NUMBER(12,2) NOT NULL;
ALTER TABLE Customer_receipt
ADD CONSTRAINT FK_RC
FOREIGN KEY (Room_charges) REFERENCES Room_Details (Room_charges);
As a frame challenge.
Can anyone help me resolve it?
Yes, do not violate Third Normal Form and do not duplicate data by storing Total_Charges, Service_Charges or Room_Charges in the Customer_Receipt table when the data is already stored in the Service_Details and Room_Details tables.
If you are storing the same data in two locations then you are likely get into the situation where the data is inconsistent between those two location; just store each piece of data in a single location so there is a single source of truth in your database.
CREATE TABLE Customer_Receipt
(
Receipt_no VARCHAR2(12)
CONSTRAINT custreceipt__recno__pk PRIMARY KEY,
Booking_no CONSTRAINT custreceipt__bookingno__fk REFERENCES Room_booking
NOT NULL
);
CREATE TABLE Services_Details
(
Receipt_no CONSTRAINT servicedetails__recno__fk REFERENCES Customer_receipt
NOT NULL,
Service_offered VARCHAR2(8)
NOT NULL,
Service_charges NUMBER(12,2),
CONSTRAINT servicedetails__recno_servoff__pk PRIMARY KEY(Receipt_no, Service_offered)
);
CREATE TABLE Room_Details
(
Receipt_no CONSTRAINT roomdetails__recno__fk REFERENCES Customer_receipt
NOT NULL,
Category_name CONSTRAINT roomdetails__catname__fk REFERENCES Room_category
NOT NULL,
Days_stayed INT,
Room_charges NUMBER(12,2),
CONSTRAINT roomdetails__recno_catname__pk PRIMARY KEY(Receipt_no, Category_name)
);
If you want to display the Total_Charges, Service_Charges and Room_Charges then use a JOIN and get the data from the related tables. Something like:
SELECT cr.*,
COALESCE(s.service_charges, 0) AS service_charges,
COALESCE(r.room_charges, 0) AS room_charges,
COALESCE(s.service_charges, 0) + COALESCE(r.room_charges, 0)
AS total_charges
FROM customer_receipt cr
LEFT OUTER JOIN (
SELECT receipt_no,
SUM(service_charges) AS service_charges
FROM services_details
GROUP BY receipt_no
) s
ON cr.receipt_no = s.receipt_no
LEFT OUTER JOIN (
SELECT receipt_no,
SUM(days_stayed * room_charges) AS room_charges
FROM room_details
GROUP BY receipt_no
) r
ON cr.receipt_no = r.receipt_no;
Or create a view (or a materialized view).

How to fix "ERROR: FK name length exceeds maximum allowed length(30)" in SQL Developer Data Modeller

I'm trying to turn the Logical Model of my Database into a DDL script, but I don't know how to fix this error in the DDL script or Data Modeller:-- ERROR: FK name length exceeds maximum allowed length(30)
It seems to be based on my junction-table's Primary Key, which is made up from two Foreign Keys from the two neighboring tables.
I have tried changing the names of the Primary Keys in the neighboring tables, but when I try to generate a NEW DDL script with Data Modeler, it still generates the old script.
Here's the sections of code that create the 3 tables and link them together:
CREATE TABLE items (
item_no NUMBER (8) NOT NULL,
"year" DATE,
price NUMBER (20,2)
);
ALTER TABLE items ADD CONSTRAINT items_pk PRIMARY KEY ( item_no );
CREATE TABLE purchase_order (
order_no NUMBER(8) NOT NULL,
quantity INTEGER,
item_description VARCHAR2(200),
unit_price NUMBER(20,2),
total NUMBER(20,2),
order_date DATE,
sales_person_code VARCHAR2(5) NOT NULL,
supplier_id NUMBER(3) NOT NULL
);
ALTER TABLE purchase_order ADD CONSTRAINT purchase_order_pk PRIMARY KEY ( order_no );
CREATE TABLE purchase_order_items (
purchase_order_order_no NUMBER(8) NOT NULL,
items_item_no NUMBER(8) NOT NULL
);
ALTER TABLE purchase_order_items ADD CONSTRAINT purchase_order_items_pk PRIMARY KEY ( items_item_no,
purchase_order_order_no );
ALTER TABLE purchase_order_items
ADD CONSTRAINT purchase_order_items_items_fk FOREIGN KEY ( items_item_no )
REFERENCES items ( item_no );
-- ERROR: FK name length exceeds maximum allowed length(30)
ALTER TABLE purchase_order_items
ADD CONSTRAINT purchase_order_items_purchase_order_fk FOREIGN KEY ( purchase_order_order_no )
REFERENCES purchase_order ( order_no );
ALTER TABLE purchase_order
ADD CONSTRAINT purchase_order_sales_person_fk FOREIGN KEY ( sales_person_code )
REFERENCES sales_person ( code );
ALTER TABLE purchase_order
ADD CONSTRAINT purchase_order_supplier_fk FOREIGN KEY ( supplier_id )
REFERENCES supplier ( id );
So I'm not sure exactly what FK name length is too long and what I need to change in the script to fix this error.
Oracle limits identifiers to 30 characters, so
purchase_order_items_purchase_order_fk needs to be shorted. Perhaps to something like poi_purchase_porder_fk.

ORA-01748: only simple column names allowed here in Oracle

What I am trying to do ?
I am trying to create two tables and at the same time i am trying to link them together using foreign and primary keys. However I successfully create my parent table ( Student with primary key ) but failed to create child table ( Attendence with foreign key ).
What is the problem ?
I get the following error while creating Attendence table:
ERROR at line 5: ORA-01748: only simple column names allowed here
My code:
Student table:
create table Student (
ST_ROLLNO NUMBER(6) constraint s_pk primary key,
ST_NAME VARCHAR(30) not null,
ST_ADDRESS varchar(35) not null
);
Attendence table:
create table Attendence (
ST_ROLLNO NUMBER(6),
ST_DATE VARCHAR(30) not null,
ST_PRESENT_ABSENT varchar(1) not null,
constraint f_pk Attendence.ST_ROLLNO foreign key references Student(ST_ROLLNO)
);
Your foreign key constraint syntax is wrong; it should be:
constraint f_pk foreign key (ST_ROLLNO) references Student(ST_ROLLNO)
You are preceding the FK column name with the table name, which is wrong in itself, but also have it in the wrong place.
create table Student (
ST_ROLLNO NUMBER(6) constraint s_pk primary key,
ST_NAME VARCHAR(30) not null,
ST_ADDRESS varchar(35) not null
);
Table STUDENT created.
create table Attendence (
ST_ROLLNO NUMBER(6),
ST_DATE VARCHAR(30) not null,
ST_PRESENT_ABSENT varchar(1) not null,
constraint f_pk foreign key (ST_ROLLNO) references Student(ST_ROLLNO)
);
Table ATTENDENCE created.
According to oracle documentation,
ORA ERR
ORA-01748 only simple column names allowed here
The following is the cause of this error:
This SQL statement does not allow a qualified column name, such as
username.table.column or table.column.
Action you can take to resolve this issue: Remove the qualifications
from the column and retry the operation.
In your case, you are trying to refer to the table name while defining a constraint -
Attendence.ST_ROLLNO - WRONG.
It must contain a simple name without the table name or schema name.

SQL: Missing Parenthesis

I have tried editing the command and looking at other questions in order to answer this question, but I still get the dreaded
ORA-00907: missing right parenthesis.
Here is my code. Is there any key word that I may need to drop here? Thanks
CREATE TABLE Loan
(
LoanID INT IDENTITY ( 1, 1 ) UNIQUE,
BranchID INT NOT NULL REFERENCES Branch(BranchID) ON DELETE CASCADE,
LoanNumber CHAR(20) NOT NULL UNIQUE,
LoanType VARCHAR(30) NOT NULL,
Amount MONEY NOT NULL,
ModifiedDate DATETIME DEFAULT (getdate()),
PRIMARY KEY ( LoanID )
);
The following ddl is syntactically correct. Of course, you have to check whether that statement really produces what you want ( in particular the IDENTITY keyword in your original statement is not accounted for ):
CREATE TABLE Loan
(
LoanID INTEGER NOT NULL PRIMARY KEY
, BranchID INTEGER NOT NULL CONSTRAINT tl_fk_branchid REFERENCES Branch(BranchID) ON DELETE CASCADE
, LoanNumber CHAR(20) NOT NULL CONSTRAINT tl_u_loannumber UNIQUE
-- right padded to length of 20 with blanks
, LoanType VARCHAR2(30) NOT NULL
, Amount Number(*,4) NOT NULL
-- cf. http://stackoverflow.com/a/29014422, changed per #BobJarvis' comment
, ModifiedDate DATE DEFAULT SYSDATE
);
The syntax deviations are as follows:
IDENTITYkeyword
inline constraint specification
datatype to represent date and time
datatype for string content
stand-in for money datatype
current datetime

Invalid table name without using a reserved word?

I'm creating a table using Oracle SQL, and when trying to create a table called 'Card' I keep getting the error that it's an invalid table name. Here's my code:
CREATE TABLE Card
(
CardNumber varchar2(20) Not Null,
CardType varchar2(5) Not Null,
CONSTRAINT CustomerIDForeignKey FOREIGN KEY (CustomerID) REFERENCES (Customer),
CONSTRAINT CardTypeConstraint CHECK (CardType='Credit' or CardType='Debit' or CardType='Gift')
)
And here's the error code I'm getting:
Error starting at line : 1 in command -
CREATE TABLE Card
(
CardNumber varchar2(20) Not Null,
CardType varchar2(5) Not Null,
CONSTRAINT CustomerIDForeignKey FOREIGN KEY (CustomerID) REFERENCES (Customer),
CONSTRAINT CardTypeConstraint CHECK (CardType='Credit' or CardType='Debit' or CardType='Gift')
)
Error report -
SQL Error: ORA-00903: invalid table name
00903. 00000 - "invalid table name"
*Cause:
*Action:
Any help would be appreciated! I didn't find 'Card' on the list of Oracle SQL's reserved words, so I'm not sure what the issue is. Thank you!
You need to add column CustomerId to Card table and change refrences to table_name(column_name):
SqlFiddleDEMO
CREATE TABLE Customer(CustomerID INT PRIMARY KEY);
CREATE TABLE Card(
CardNumber varchar2(20) Not Null,
CardType varchar2(5) Not Null,
CustomerId INT NOT NULL,
CONSTRAINT CustomerIDForeignKey FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerId),
CONSTRAINT CardTypeConstraint CHECK (CardType IN ('Credit', 'Debit' ,'Gift'))
);
Also you can replace:
CHECK (CardType='Credit' or CardType='Debit' or CardType='Gift')
with:
CHECK (CardType IN ('Credit', 'Debit' ,'Gift'))
You can think about:
Adding Primary Key to Card table
Hashing/encrypting card number (do not store as plain text)
Creating CreditCardType dictionary table