Adding column with primary key in existing table - sql

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

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

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.

create primary key on existing table without primary key in SQL Server

I am trying to assign an existing column to be the primary key(and another in different table as foreign key) in a table without primary key. I tried this:
Altering a column: null to not null, and it didn't work. The column contains number, text and null values.
Could someone create a step-by-step guide and share with everyone here?
This is the error message:
Msg 8152, Level 16, State 13, Line 2
String or binary data would be truncated.
It would great if you can help interpret the error message.
Thanks!
To add a primary key to an existing table you can do this:
ALTER TABLE yourTableName ADD yourColumnName INT NOT NULL PRIMARY KEY IDENTITY(1, 1)
which will add a new column and automatically populate it with unique integer values starting from one. To add a foreign key to another table use similar syntax to above but don't make the column NOT NULL until you've worked out how to link it to your existing primary key - which is a whole different question.
ALTER TABLE yourOtherTable ADD yourFKColumnName INT WITH CONSTRAINT [FK_SensibleForeignKeyName] FOREIGN KEY ([yourFKColumnName]) REFERENCES yourTableName([yourColumnName])
I haven't tested it but that should be pretty close to what you need.
Just do a
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable
PRIMARY KEY CLUSTERED (YourColumnHere)
and you're done. This requires that YourColumnHere is a non-nullable column, of course.

SQL Alter Statement for Primary Key Column

I am having a problem making the column I am adding NOT NULL using the SQL ALTER statement. I am fairly novice with SQL so any guidance would be great. I am using SQL Sever 2008 and I am receiving an error stating that the column cannot be added to the table because it does not allow nulls and does not specify a default definition. I already have data in the table and I am just looking to add an incremental primary key.
This is the SQL I am using to generate the column
ALTER TABLE EPUpdates.GenInfo_OpType3
ADD KeyOpType Integer NOT NULL
This is the SQL I am using to make it a Primary Key/ Identity Column
ALTER TABLE EPUpdates.GenInfo_OpType3
ADD PRIMARY KEY(KeyOpType)
try to add a default value to your column, but if you want to make it as a primary key, the values must be different for each row, so you have to update these value after creating the new column and before create your primary index.
ALTER TABLE EPUpdates.GenInfo_OpType3
ADD KeyOpType Integer NOT NULL Default 0
If your trying to to add an incremental primary key then try this
ALTER TABLE EPUpdates.GenInfo_OpType3
ADD KeyOpType INT NOT NULL IDENTITY (1,1) PRIMARY KEY

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)