How do I make a Table's Attribute a Foreign Key within that Table? - sql

I had to write the SQL to create the tables, attributes, and primary & foreign keys in this ERD:
http://imgur.com/VYZbwr6
In the table 'Financial_Transactions' in the ERD there is a attribute called 'previous_transaction_id' and another attribute called 'transaction_id'. In this table 'previous_transaction_id' is a Foreign Key for this table in addition to being an attribute. It references the last 'transaction_id' in the table.
Here is my SQL for the 'financial_transactions' table:
CREATE TABLE financial_transactions(
transaction_id int IDENTITY(1,1) NOT NULL,
account_id int NOT NULL,
item_rental_id int NOT NULL,
previous_transaction_id int,
transaction_type_code int NOT NULL,
transaction_date date NOT NULL,
transaction_amount money NOT NULL,
transaction_comment varchar(512) NOT NULL);
ALTER TABLE financial_transactions ADD CONSTRAINT pk_financial_transactions PRIMARY KEY (transaction_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_accounts FOREIGN KEY(account_id)
REFERENCES accounts (account_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_customer_rentals FOREIGN KEY(item_rental_id)
REFERENCES customer_rentals (item_rental_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_financial_transactions FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (previous_transaction_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_transaction_types FOREIGN KEY(transaction_type_code)
REFERENCES transaction_types (transaction_type_code);
When I run my SQL (includes statements for each table in the script) I get these errors:
"Msg 1776, Level 16, State 0, Line 87
There are no primary or candidate keys in the referenced table 'financial_transactions' that match the referencing column list in the foreign key 'fk_financial_transactions_financial_transactions'.
Msg 1750, Level 16, State 0, Line 87
Could not create constraint. See previous errors."
All other statements execute normally.
What am I doing wrong?
*I used this statement originally under CREATE TABLE: previous_transaction_id int NOT NULL,
However, it resulted in the same error and when searching I saw a similar question that was fixed by removing the NOT NULL.

Here
ALTER TABLE financial_transactions ADD CONSTRAINT
fk_financial_transactions_financial_transactions
FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (previous_transaction_id);
You have a column referencing itself. Was that your intent or did you want to reference the transaction_id?

There is nothing wrong with defining a foreign key to the same table but you have a column referencing itself.
Try replacing:
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_financial_transactions FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (previous_transaction_id);
With:
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_financial_transactions FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (transaction_id);

Related

How do I change a column I created a while ago in sql to foreign key

I need to change multiple tables to foreign keys. I have used the command
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES transaction_id(item_rental_id);
The table name was financial_transactions and the column name was item_rental_id. It gives me an error saying:
Foreign key 'FK__financial__item___46E78A0C' references invalid table 'transaction_id'.
How do I resolve this?
Yes, this is a correct script to create a foreign key
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals(item_rental_id);
However, if you are trying to add a foreign key constraint on a table with data already in it, you have to make sure that the item_rental_id in financial_transactions table are also in the customer_rentals table. Otherwise, you will have a referential integrity error.
To illustrate:
CREATE TABLE customer_rentals_1
(item_rental_id INT,
PRIMARY KEY (item_rental_id)
);
CREATE TABLE financial_transactions_1
(transaction_id INT,
item_rental_id INT,
PRIMARY KEY (transaction_id)
);
ALTER TABLE financial_transactions_1
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals_1(item_rental_id);
The scripts above will run successfully.
CREATE TABLE customer_rentals_2
(item_rental_id INT,
PRIMARY KEY (item_rental_id)
);
CREATE TABLE financial_transactions_2
(transaction_id INT,
item_rental_id INT,
PRIMARY KEY (transaction_id)
);
INSERT INTO financial_transactions_2
VALUES (1000, 9999);
ALTER TABLE financial_transactions_2
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals_2(item_rental_id);
But, this will have the following error since item_rental_id 9999 is not present in customer_rentals_2 table
Msg 547, Level 16, State 0, Line 31
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__financial__item___76969D2E". The conflict occurred in database "TESTDB", table "dbo.customer_rentals_2", column 'item_rental_id'.
You have to give second table name
both way can do it
1. Add reference without name
ALTER TABLE financial_transactions
ADD FOREIGN KEY (item_rental_id) REFERENCES customer_rentals(item_rental_id);
2.Add reference with a name
ALTER TABLE financial_transactions
ADD CONSTRAINT FK_Financial_Transactions_Customer_Rental_Item_Rental_ID
FOREIGN KEY (item_rental_id) REFERENCES Customer_rentals(item_rental_id);

How to add foreign key to an existing column in SQL Server 2012

I am trying to add foreign key to my existing column using below query
ALTER TABLE Sub_Category_Master
ADD FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
but I'm getting an error
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Sub_Categ__Categ__5812160E". The conflict occurred in database "shaadikarbefikar_new", table "shaadikarbefikar.Category_Master", column 'Category_ID'.
Well, the error clearly tells you that Category_ID in your Sub_Category_Master table contains some values that are not present in Category_Master (column Category_ID). But that's exactly the point of having a foreign key constraint - making sure your child table (Sub_Category_Master) only uses defined values from its parent table.
Therefore, you must fix those "voodoo" values first, before you're able to establish this foreign key relationship. I would also strongly recommend to explicitly name that constraint yourself, to avoid those system-generated, but not really very useful constraint names like FK__Sub_Categ__Categ__5812160E:
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FK_SubCategoryMaster_CategoryMaster
FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FKSub_Category_Master_Category_ID FOREIGN KEY (Category_ID)
REFERENCES Category_Master(Category_ID);
CREATE TABLE Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

Can't add foreign key constraint to table

CREATE TABLE CUSTOMER
(
CNUM VARCHAR(25) NOT NULL,
CNAME VARCHAR(75) NOT NULL,
CTYPE VARCHAR(20) NOT NULL,
CONSTRAINT CUSTOMER_PK PRIMARY KEY(CNUM),
CONSTRAINT CHECK_CTYPE CHECK(CTYPE IN('INDIVIDUAL', 'INSTITUTION'))
);
CREATE TABLE CREDIT_TERM
(
CREDITSTATUS VARCHAR(20) NOT NULL,
STARTDATE DATE NOT NULL,
ENDDATE DATE NOT NULL,
CONSTRAINT CREDIT_TERM_PK PRIMARY KEY(CREDITSTATUS)
);
insert into CREDIT_TERM values('ONE-MONTH','15-05-2015','15-06-2015');
insert into CREDIT_TERM values('TWO-MONTH','15-05-2015','15-06-2015');
insert into CREDIT_TERM values('THREE-MONTH','15-05-2015','15-06-2015');
ALTER TABLE CUSTOMER
ADD CONSTRAINT CUSTOMER_FK_CREDITSTATUS
FOREIGN KEY(CREDITSTATUS) REFERENCES CREDIT_TERM(CREDITSTATUS);
I am trying to add a foreign key constraint, but I don't understand why I get this error:
ERROR at last line :
ORA-00904: "CREDITSTATUS": invalid identifier
As I noted in the comments, your customer table does not have a creditstatus column. You'd first have to add it:
ALTER TABLE customer ADD creditstatus VARCHAR2(20);
And then make it a foreign key, with the statement you already have.
You're trying to add a foreign key constraint for a foreign key named CREDITSTATUS on the CUSTOMER table. However, the CUSTOMER table doesn't have a foreign key for CREDITSTATUS.
You'll have to create a foreign key in CUSTOMER for CREDITSTATUS, then rerun the last line to add the constraint.
EDIT
Use ALTER TABLE to add the column to CUSTOMER:
ALTER TABLE CUSTOMER ADD CREDITSTATUS VARCHAR(20);
Docs:
http://www.techonthenet.com/oracle/tables/alter_table.php
You can add the column and the foreign key constraint in one statement:
alter table customer add (
creditstatus varchar2(20) constraint customer_fk_creditstatus references credit_term
);
A few notes. First, I enclosed the column definition in parentheses. It may work without them, but the official syntax seems to require them. http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_3001.htm#i2103924
Second, in an in-line constraint (defined at the column level, not at the table level), you may not use the words FOREIGN KEY. The word REFERENCES already identifies the constraint type. Third, if you reference the PRIMARY KEY of the referenced table, you are not required to (but you may if you wish) name the referenced column in the referenced table. If you don't name the column, the PRIMARY KEY of the referenced table will be used by default - which is what you want anyway, in the vast majority of cases.

SQL ALTER TABLE ON DELETE CASCADE

I have the following tables:
CREATE TABLE BOOK_AUTHORS
(Book_id CHAR(20) NOT NULL,
AuthorName VARCHAR(30) NOT NULL,
PRIMARY KEY (Book_id, AuthorName),
FOREIGN KEY (Book_id) REFERENCES BOOK (Book_id));
CREATE TABLE BOOK_COPIES
(Book_id CHAR(20) NOT NULL,
Branch_id CHAR(20) NOT NULL,
No_of_copies NUMBER,
PRIMARY KEY (Book_id, Branch_id),
FOREIGN KEY (Book_id) REFERENCES BOOK (Book_id),
FOREIGN KEY (Branch_id) REFERENCES LIBRARY_BRANCH (Branch_id));
I want to add ON DELETE CASCADE constraints to the both of them:
The first time I tried it said it worked. That file looks like:
ALTER TABLE "BOOK_AUTHORS"
ADD CONSTRAINT "fk_test"
FOREIGN KEY ("Book_id")
REFERENCES "BOOK" ("Book_id")
ON DELETE CASCADE;
Then I went through and made two separate tables for the two foreign keys in the second table:
ALTER TABLE "BOOK_COPIES"
ADD CONSTRAINT "fk_test1"
FOREIGN KEY ("Book_id")
REFERENCES "BOOK" ("Book_id")
ON DELETE CASCADE;
ALTER TABLE "BOOK_COPIES"
ADD CONSTRAINT "fk_test2"
FOREIGN KEY ("Branch_id")
REFERENCES "LIBRARY_BRANCH" ("Branch_id")
ON DELETE CASCADE;
However, upon doing so I got the errors
"Book_id" invalid identifier
and then
"Branch_id" invalid identifier
I don't know what I did wrong. I then went back and did the first alter table again (the one that I originally thought worked) and it gave me the same error message ("Book_id" invalid identifier). Can someone help me add these constraints? I also have five other tables to add these constraints to.
If you put double quotes around your identifiers (like you did in
ALTER TABLE "BOOK_COPIES"
ADD CONSTRAINT "fk_test1"
FOREIGN KEY ("Book_id")
REFERENCES "BOOK" ("Book_id")
ON DELETE CASCADE;
) your identifiers (e.g. "Book_id" in this case) become case-sensitive.
So either you'll have to change your table definition and rename the column to "Book_id" or (much preferably IMHO) just get rid of the double quotes in your constraint definition:
ALTER TABLE BOOK_COPIES
ADD CONSTRAINT fk_test1
FOREIGN KEY (Book_id)
REFERENCES BOOK (Book_id)
ON DELETE CASCADE;
First of all let me clear one thing, You cant add on delete cascade to an already existing foreign key constraint, as shown in docs you can only change its state which means enable or disable, in case if you need to add then drop the constraint first. This question is asked twice and still repeating please moderators have a glance on this. Here are links that has already solved your problem. first , second and this third and who knows how many questioned asked on on delete cascade.
Put doublequotes (") around your table and column names.
I added table "BOOK" and table "LIBRARY_BRANCH":
CREATE TABLE "BOOK"
("Book_id" CHAR(20) NOT NULL,
"BookName" VARCHAR(30) NOT NULL,
PRIMARY KEY ("Book_id"));
CREATE TABLE "BOOK_AUTHORS"
("Book_id" CHAR(20) NOT NULL,
"AuthorName" VARCHAR(30) NOT NULL,
PRIMARY KEY ("Book_id", "AuthorName"));
CREATE TABLE "LIBRARY_BRANCH"
("Branch_id" CHAR(20) NOT NULL,
"Branch_name" VARCHAR(50),
"Address" VARCHAR(100),
PRIMARY KEY ("Branch_id"));
CREATE TABLE "BOOK_COPIES"
("Book_id" CHAR(20) NOT NULL,
"Branch_id" CHAR(20) NOT NULL,
"No_of_copies" NUMBER,
PRIMARY KEY ("Book_id", "Branch_id"));
ALTER TABLE "BOOK_AUTHORS"
ADD CONSTRAINT "fk_test"
FOREIGN KEY ("Book_id")
REFERENCES "BOOK" ("Book_id")
ON DELETE CASCADE;
ALTER TABLE "BOOK_COPIES"
ADD CONSTRAINT "fk_test1"
FOREIGN KEY ("Book_id")
REFERENCES "BOOK" ("Book_id")
ON DELETE CASCADE;
ALTER TABLE "BOOK_COPIES"
ADD CONSTRAINT "fk_test2"
FOREIGN KEY ("Branch_id")
REFERENCES "LIBRARY_BRANCH" ("Branch_id")
ON DELETE CASCADE;
sqlfiddle demo

Adding constraints on table

I am new to SQL Oracle.I have the following script:
create table students(
sid char(10),
honors char(10) not null,
primary key (sid),
Constraint studentConst foreign key (honors) references Courses(cid),
);
create table Courses(
cid char(10),
grader char(20) not null,
primary key (cid),
Constraint CoursesConst foreign key (grader) references students(sid),
);
SET CONSTRAINT studentConst,CoursesConst DEFERRED;
I get the following error on running the above script:
SQL Error: ORA-00904: : invalid identifier on line 5. Why do I get this error ?
I don't think you can create a foreign key constraint on a table that doesn't yet exist.
Since you have a two-way constraint, you'll need to create the first table without the constraint, then add it with alter table after the second table has been created.
Deferred constraints are for checking data. Deferral simply means the check won't be carried out until the end of the transaction. It does not mean "defer the creation of the constraints so I can set up a circular reference" :-)
It looks like line 5 is trying to reference Courses(cid). However, at this point, the Courses table does not exist, as it's created in the following SQL block.
Try creating dependent tables first.
Add the constraint after the tables are built. You can do this using an alter table statement:
create table students(
sid char(10),
honors char(10) not null,
primary key (sid)
);
create table Courses(
cid char(10),
grader char(20) not null,
primary key (cid),
Constraint CoursesConst foreign key (grader) references students(sid)
);
alter table students add constraint studentConst foreign key (honors) references Courses(cid)
The SQLFiddle is here.