How do i add foreign key to existing table? - sql

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)).

Related

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.

Adding Constraint with multiple foreign keys

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".

Adding column with primary key in existing table

I am trying to add primary key to newly added column in existing table name Product_Details.
New Column added: Product_Detail_ID (int and not null)
I am trying add primary key to Product_Detail_ID (please note: there are no other primary or foreign key assigned to this table)
I am trying with this query but getting error.
ALTER TABLE Product_Details
ADD CONSTRAINT pk_Product_Detils_Product_Detail_ID PRIMARY KEY(Product_Detail_ID)
GO
Error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.Product\_Details' and the index name 'pk\_Product\_Detils'. The duplicate key value is (0).
Am I missing something here? I am using SQL Server 2008 R2. I would appreciate any help.
If you want SQL Server to automatically provide values for the new column, make it an identity.
ALTER TABLE Product_Details DROP COLUMN Product_Detail_ID
GO
ALTER TABLE Product_Details ADD Product_Detail_ID int identity(1,1) not null
GO
ALTER TABLE Product_Details
add CONSTRAINT pk_Product_Detils_Product_Detail_ID primary key(Product_Detail_ID)
GO
In mysql, I was able to achieve with following query
ALTER TABLE table_name ADD new_column int NOT NULL AUTO_INCREMENT primary key
Add Primary Key to First Position
ALTER TABLE table_name
ADD column_name INT PRIMARY KEY AUTO_INCREMENT FIRST;
Reference: Stack Overflow | Tech On The Net
You are getting the error because you have existing data that does not fullfill the constraint.
There are 2 ways to fix it:
clean up the existing data before adding the constraint
add the constraint with the "WITH NOCHECK" option, this will stop sql server checking existing data, only new data will be checked
ALTER TABLE Jaya
ADD CONSTRAINT no primary key(No);
here Jaya is table name,
no is column name,
ADD CONSTRAINT is we giving the primary key keyword
If you want to add a new column say deptId to the existing table say department then you can do it using the below code.
ALTER TABLE department ADD COLUMN deptID INT;
it will create your new column named deptID.
now if you want to add constraint also along with new column while creating it then you can do it using the below code. In the below code I am adding primary key as a constraint. you can add another constraint also instead of primary key like foreign key, default etc.
ALTER TABLE department ADD COLUMN deptID INT NOT NULL ADD CONSTRAINT PRIMARY KEY(deptID);
k. friend
command:
sql> alter table tablename add primary key(col_name);
ex: alter table pk_Product_Detils add primary key(Product_Detail_ID);

Alter table & Add UNIQUE key results in an error

I have a table called Animal. AnimalId is the primary key & I wanted to set the column AnimalType_id as UNIQUE (I have an AnimalType table and need to set a foreign key here)
ALTER TABLE Animal
ADD UNIQUE Animal.AnimalType_id int
There already is data in both tables, because of that I can't drop the table.
This however results in an error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '.'.
See the documentation for how to add a table constraint.
ALTER TABLE Animal ADD CONSTRAINT UQ_Animal_AnimalTypeId UNIQUE (AnimalType_id)
It sounds like AnimalType_id is a foreign key so I just wanted to check you understood that by making this column unique, you're making the relationship one-one - you'll only be able to have one animal of each type.
Since you're getting an error adding the unique constraint, I'm going to suggest that you actually want a foreign key instead of a unique constraint:
ALTER TABLE Animal
ADD CONSTRAINT FK_Animal_AnimalType
FOREIGN KEY
(
AnimalType_id
)
REFERENCES AnimalType
(
id
)
I've had to guess at the name of the AnimalType table name and it's primary key column name - please change these if they are incorrect.
If you get into the habit of giving names to all objects (even constraints) that you create, you will have easier time later when you need to disable, drop, or alter the constraint:
ALTER TABLE Animal ADD CONSTRAINT UQ_Animal_Type UNIQUE (AnimalType_id)
It is also possible to get a more flexible constraint-like effect from creating a unique index.
I think you are trying to do this:
ALTER TABLE Animal
ADD COLUMN AnimalType_id int;
It seems the data in the column is not unique.
when you create a unique constraint on a column, you can not have any duplicate entries (you can have at most one null)
try this
ALTER TABLE table_name ADD CONSTRAINT UNIQUE (column_name)

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.