Adding Constraint with multiple foreign keys - sql

I have a SQL database opened with visual studio, and I need to add some constraints to a table already created. I need a foreign key, which already has a foreign key from a third table. To explain better ,
Table ANIMALI needs a foreign key from table GABBIA, which has already a foreign key from table STANZA. This was the code I came up with:
ALTER TABLE ANIMALE ADD CONSTRAINT REF_ANIMA_GABBI_FK FOREIGN KEY (n_stanza, n_gabbia) REFERENCES GABBIA(n_stanza, n_gabbia);
This gives me an error, n_stanza is a column id not valid. I think it's about the fact that the ID for the class GABBIA is taken from joining n_gabbia and n_stanza, the latter being a key in class STANZA.
Can anyone help me out?

In order for your ALTER TABLE statement to work as written, both tables (not classes) "ANIMALE" and "GABBIA" must include the columns "n_stanza" and "n_gabbia".
In addition, in the table "GABBIA", there must be either a primary key constraint or a unique constraint on the pair of columns "n_stanza" and "n_gabbia". That is, you need something like either primary key (n_stanza, n_gabbia) or unique (n_stanza, n_gabbia) in the table "GABBIA".

Related

How do i add foreign key to existing table?

I am trying to add a foreign key to the table STUDENTS from the table PROGRAMS
ALTER TABLE COLLEGE.dbo.STUDENTS
ADD FOREIGN KEY(ProgramId) REFERENCES
PROGRAMS(ProgramId);
But it giving the following error :
Foreign key 'ProgramId' references invalid column 'ProgramId' in referencing table 'STUDENTS'
Not sure what i am doing wrong here any tip or solution would be a great help.
The column needs to exist in the table before it can be used for a foreign key reference. So I assume you intend something like:
ALTER TABLE COLLEGE.dbo.STUDENTS
ADD ProgramId INT; -- have to guess at the type
ALTER TABLE COLLEGE.dbo.STUDENTS
ADD FOREIGN KEY (ProgramId) REFERENCES
PROGRAMS(ProgramId);
You appear to want to add a column with a related foreign key.
In SQL Server, you can do this in a single commad, like so:
ALTER TABLE COLLEGE.dbo.STUDENTS
ADD ProgramId INTEGER
CONSTRAINT StudentsProgramIdFk FOREIGN KEY(ProgramId) REFERENCES PROGRAMS(ProgramId);
You should adjust the datatype of the column to your exact need. The key point is that the new column must have the same datatype as the column it references (that is PROGRAMS(ProgramId)).

SQL relation 1 key not 2 keys between tables

I want to define a foreign key constraint between the table Speler and the table Wedstrijd. I want the key on the Wedstrijd table, but when I use this code in my SQL console:
ALTER TABLE Speler
ADD FOREIGN KEY (idSpeler) REFERENCES Wedstrijd(idWedstrijd);
It puts a key on the table Speler and on the table Wedstrijd
Thanks for your time!
ALTER TABLE Wedstrijd
ADD FOREIGN KEY (idWedstrijd) REFERENCES Speler(idSpeler);
Instead of "solving" what you perceive as your problem, I think you have a different problem:
By mapping idSpeler to idWedstrijd, you are basically saying that a Speler (Player) is equal to a Wedstrijd (Match). That becomes a 1:1 relation which is then shown as a line with two yellow 'key'-endings (assuming you are using SQL Server).
It is very likely to me that instead you need to create a linking table WedstrijdSpeler that sits between the other two tables.
Then the new table WedstrijdSpeler needs to be given 2 Foreign Keys:
WedstrijdSpeler.idWedstrijd -> Wedstrijd.idWedstrijd
WedstrijdSpeler.idSpeler -> Speler.idSpeler.
Then you can give WedstrijdSpeler either a combined Primary Key (containing both fields idWedstrijd and idSpeler), or you can add a third field idWedstrijdSpeler and make that the Primary Key. Either approach will do, it is up to you.

Why can't I add this foreign key?

I'll post only the main part. I have two tables, each one has to have the PK of the other as a FK.
CREATE TABLE apartment
(
cod_apartment INT NOT NULL PRIMARY KEY,
cod_offer INT NOT NULL
);
CREATE TABLE offer
(
cod_offer INT NOT NULL PRIMARY KEY,
cod_apartment INT NOT NULL
);
First I inserted the values on both tables and it was working, I could even search using "select * from...". But then I tried to add the foreign key:
This worked.
ALTER TABLE offer
ADD FOREIGN KEY (cod_apartment ) REFERENCES apartment;
And this not.
ALTER TABLE apartment
ADD FOREIGN KEY (cod_offer) REFERENCES offer;
This is the error message:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__apartment__cod_offer__6383C8BA". The conflict occurred in database "kleber_apartment", table "dbo.offer", column 'cod_offer'.
The problem is, every time I try to execute, the FK name changes. And this FK actually doesn't exist. I already dropped both tables and tried to insert the values again, but the same happens.
What could be?
That means you're trying to add a foreign key when existing data doesn't obey that constraint. So you have a record in your apartment table where the cod_offer column does not match any value in the cod_apartment table.
Adding a foreign key not only constrains future data, but it requires that any existing data must also follow the rule.
And regarding the 6383C8BA, whenever you add a constraint without giving it a name, SQL Server picks one for you. Personally, I'd recommend something like:
alter table dbo.apartment
add constraint FK_apartment__cod_offer
foreign key (cod_offer) references dbo.offer (cod_offer);
This lets you define names the way you want, and is a little more clear about what you're actually building.

Oracle SQL Foreign Key constraint that ignores null or historic values

I am trying to add a constrain to a database table that I want to modify. I want to add a constraint on a column so it references a primary key of another tables. Easy enough, I just have to add a foreign key constraint. The problem is that the column already has some values that are null or something that is not part of the table I will be referencing.
My question is how do I add a constraint that references a primary key but can also accept null values (the primary key always has a value) and how to ignore the existing values so far. Is it possible? If the second part is not, I am thinking I could always write a script that updates all the nonsense values (they have a format of sort if that I can reg ex) to null so they only thing I have to figure out is how to add a foreign key constraind that also accepts null values
Firstly, there's nothing stopping you from adding a referential constraint on a column that has NULLs - foreign key constraints are only enforced for non-NULL values.
Secondly, if there are existing values that do not exist in the parent table, and you can't fix them, you do have the option in Oracle to make the constraint only validated for newly inserted or updated rows, using the NOVALIDATE option, e.g.
ALTER TABLE x ADD CONSTRAINT fk FOREIGN KEY (id) REFERENCES parent (id) NOVALIDATE;
The only downside to using the NOVALIDATE option is that the query optimizer will not rely on the FK constraint, and will execute queries with the assumption that there may be rows that do not have a matching parent row.
It would be a good idea if you are able to fix the missing values, afterwards to alter the constraint to VALIDATE.
Primary keys can not contain NULL values in all databases (proof)
To add a foreign key you should do something like:
ALTER TABLE table1
ADD CONSTRAINT fk_table1_2
FOREIGN KEY (column1)
REFERENCES table2(column2);

MySQL Error Code: 1005

I am trying to add foreign keys to my table but receiving this error.
Error Code: 1005 Can't create table 'william.#sql-88c_3' (errno: 150)
I have 3 tables. employee, client and Contract.
employe [employee_no PK] , Client[customer_no PK] contract [contract_no PK]
I want to have Foreign keys for contract as contract [contract_no PK, employee_no FK], customer_no FK]
I tried to do directly it failed, I am now trying the alter statement.Is anything wrong with the Alter script?
ALTER TABLE contract
ADD CONSTRAINT `employee_no_fk2` FOREIGN KEY (`employee_no`) REFERENCES `employee`
(`employee_no`);
ALTER TABLE contract
ADD CONSTRAINT `Customer_no_fk2` FOREIGN KEY (`Customer_no`) REFERENCES `client`
(`Customer_no`);
Most of such error will be related to data type miss match or so.. If you could go through these links.. it might help you i guess.. Check-this
... also Check-this
As they say in the second link:
The first place you should look is whether the data types agree
between the foreign key and primary key columns.
mysql> SHOW engine innodb STATUS;
------------------------
LATEST FOREIGN KEY ERROR
------------------------
100130 17:16:57 Error IN FOREIGN KEY CONSTRAINT OF TABLE sampledb/#sql-4a0_2:
FOREIGN KEY(member_type)
REFERENCES common_lookup(common_lookup_id):
Cannot find an INDEX IN the referenced TABLE WHERE the
referenced COLUMNS appear AS the FIRST COLUMNS, OR COLUMN types
IN the TABLE AND the referenced TABLE do NOT MATCH FOR CONSTRAINT.
make sure that one of the key field that you are trying to reference does not have an index and/or is not a primary key. and the two key fields type and/or size should be an exact match also make sure that both tables are InnoDB tables.
This can happen due to two reasons
Table creation failed because a foreign key constraint was not correctly formed or
Datatype mismatch in the constraints.
the below link would be helpful
http://dev.mysql.com/doc/refman/5.0/en/innodb-error-codes.html
Last time I encountered this, it was the constraints: referenced table key type was 'int' and referring table had 'unsigned int' referring field by mistake, instead of int.