Adding column with existing table which have primary key - sql-server

I need your help...., Please help me
I want to add a new primary key to an existing table which already has 3 columns as composite primary key. But, I do not want to drop the old primary key, since there are many records and the old primary key also have relationship with other table
When I am using this query:
alter table hem154
add indexNO uniqueidentifier default newid()
alter table hem154
add CONSTRAINT pk_hem154_indexNo PRIMARY KEY (PK_indexNO)
Note:
Hem154 ~ Table Name
indexNo ~ Column Name which will to added
I get this runtime error:
Msg 1779, Level 16, State 0, Line 1
Table 'hem154' already has a primary key defined on it.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
Please help me, how can I do it???
Thanks

Drop all primary keys and add Again all primary keys
ALTER TABLE hem154
DROP PRIMARY KEY,ADD PRIMARY KEY (col1,col2,indexNO);

You can only have one primary key per table. You can either add a second table that maps your new PK to the old PK, or drop the old PK and add the new one. Dropping the PK won't drop the columns, it just stops using them as the composite key. Any tables that were relying on the old key should probably be updated as well to support whatever answer you decide on.

First DROP existing PRIMARY KEY and ADD new composite PRIMARY KEY.
ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
GO
and then try your code

There is no easy way of doing this. From your question, I understand that you want to add one additional column to the existing Primary Key. If they have existing relationships, then it is not possible to do this, without dropping those FK constraints first. Even if you do that, you will not be able to reestablish those FK constraints again, as you have modified the PK.
If you do not need to reestablish those FK relationships, then you can do this:
Drop all FK relationships
Drop existing PK (data will not be deleted, only the constraint will be dropped)
Add new column
Recreate PK to include the new column
However, if you cannot drop the existing FK constraints, then I am afraid this is not possible

On Microsoft SQL Server Management Studio:
Select/highlight both columns
Right click either
Press "Set primary key"

Related

how to add foreign key to Azure SQL DB Table

I am stumped by an Add Constraint Foreign Key error I am encountering.
I just created TableA with a Primary Key on PLAN_ID. The table contains zero records. I am attemtpting to execute:
alter table TableB
add constraint FK_TASK_PLAN Foreign Key (TASK_PLAN_ID)
references TableA (PLAN_ID)
Which keeps returning
"Msg 547, Level 16, State 0, Line 5. The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_TASK_PLAN". The conflict occurred in database "DT_Worklist", table "dbo.TableA", column 'PLAN_ID'.
This essentially seems to be telling me I cannot create an FK on the specified column.
What am I doing wrong which is preventing me from creating this Foreign Key? Is it OK my Parent Table is empty or does it need at least one record? What about the FK column; does it need to be Not Null or does it need to have at least 1 record?
Actually, I think I figured this out... My PARENT Table which I just created is empty while my CHILD Table which was created * populated about a week ago already has values in the FK column. So there is no way to create the PK/FK relationship when the FK already contains values.....

Change Primary Key with custom identity seed on existing table SQL Server

I very new in SQL Server it's about 3 months. Now, I am stuck with a problem.
I need to change the primary key on a table with lots of data, about 10000 rows. Some other tables have relationship with this table (FK), but some tables stand alone. i wanna change the primary key and change the start identity seed with i want.
I have browsing in google but still no luck.
Can someone in here give me solution.
Thanks..
1)To DROP a PRIMARY KEY Constraint
ALTER TABLE Persons
DROP CONSTRAINT pk_PersonID
2)Alter table with new primary constarint
ALTER TABLE Persons
ADD PRIMARY KEY (pk_PersonID)

How can I drop a constraint with multiple columns as the primary key in SQL Server?

My code looks like this:
CONSTRAINT user_password_username_password PRIMARY KEY (username, password)
I need to drop this constraint because I updated the foreign keys and no longer can use password in the constraint. I also cannot simply drop the table and recreate it because it is linked to other tables. How can I drop this constraint so only username will make up the primary key?
Drop all foreign key constraints referencing the user_password_username_password constraint. Disable will not work; you must drop them. You may need to drop foreign keys that reference other unique keys on the table, but I'm not sure about that.
Drop the user_password_username_password constraint on the table.
Create a new unique/primary key constraint on the table.
Create or recreate any foreign key constraints.
I believe you can do all this in a single transaction, but if it's a large table I'd consider doing this in single user mode. You'll be dropping a primary key which causes an index rebuild for every index and constraint on the table, then potentially creating several new indexes/constraints in the foreign keys, and then creating the new primary key which again forces all the indexes and constraints on the table to rebuild.

SQL Server having a column as both PK and FK

I have not done much database design work and I was searching around for some example.
While I know the difference from a primary and foreign key, one thing that caught be off guard was that even if a Table has a primary key and is used as a foreign key in another table, as I was used the GUI SSMS tools, I noticed that I sometime end up having this
PhoneID (PK, int, not null)
While my User table
UserId(PK,FK, int, not null)
BOTH of these tables have these ID's as primary keys in those tables, along with foreign keys in other tables, but why does one of them have "PK,FK" obviously I accidentally created it, but should it be like that?
It is Possible for a Primary key to be a Foreign Key as well at the same time.
But looking at you database design, In your case I dont think it was intentional it was done by mistake. And if it wasnt done by mistake then you need to fix it.
In your dbo.PhoneType Table the column PhoneTypeID needs to be a Primary key only not a Foreign key. My guess is this was done by mistake, you wanted to create a Foreign key in your dbo.Phone table on column PhoneTypeID referencing PhoneTypeID column in dbo.PhoneType table. But somehow you end up create a foreign key constraint on the Primary key column of the dbo.Phontype table.
This Design contradicts constraints.
In simple english : The foreign Key Constraint on your dbo.PhoneType(PhoneTypeID) enforces that you cannot have a PhoneTypeID in dbo.PhoneType table unless it exists in PhoneTypeID column of dbo.Phone table.
On the other hand Foreign Key Constraint on dbo.Phone(PhoneTypeID) enforces that you cannot have a PhoneTypeID in dbo.Phone unless it exists in dbo.PhoneType(PhoneTypeID).
and same is true for the UserID column in dbo.Users table.
Solution
You need to drop the following Constraints to make it work properly.
1) In dbo.PhoneType table Drop Foreign key constraint referencing
PhoneTypeID column in dbo.phone table.
2) In dbo.Users Table drop the Drop Foreign key constraint referencing
UserID column in dbo.phone table.
It's entirely possible, yes. A primary key of a table could also be a foreign key referencing another table.
In your case, I'm not exactly sure what you did. You can check the constraints to see which column the UserId column is referencing.
As an additional note, simply adding a foreign reference to a table does not implicitly make that column a foreign key on another table. For example, just because you add FK_PhoneTypeID to the Phone table, SQL Server does not automatically make PhoneTypeID column in the PhoneType table a FK. In your statements, somewhere, it's possible that you made assignments to other columns, or even to themselves.

SQL Server update primary key that's also a foreign key in two tables

I need to update the primary key for a record but it's also the foreign key in two other tables. And I need the updated primary key to be reflected in the child tables as well.
Here is my query and the error:
begin tran
update question set questionparent = 10000, questionid= 10005 where questionid = 11000;
Error 9/4/2009 10:04:49 AM 0:00:00.000 SQL Server Database Error: The UPDATE statement conflicted with the REFERENCE constraint "FK_GoalRequirement_Question". The conflict occurred in database "numgmttest", table "dbo.GoalRequirement", column 'QuestionID'. 14 0
I don't remember how to go about doing this so that's why I'm here. Any help?
Are your relationships using
ON UPDATE CASCADE
If they are then changing the key in the primary table will update the foreign keys.
e.g.
ALTER TABLE Books
ADD CONSTRAINT fk_author
FOREIGN KEY (AuthorID)
REFERENCES Authors (AuthorID) ON UPDATE CASCADE
You may:
disable enforcing FK constraints temporarily (see here or here)
update your PK
update your FKs
enable back enforcing FK constraints
do it all within a transaction and make sure that if transaction fails, you roll it back properly and still enforce the FK constraints back.
But... why do you need to change a PK? I hope this is an action that is executed rarely (legacy data import or something like that).
If you would like to set the Cascade rule graphically then Set Cascade Rule on SQL Management Studio
Open table in design mode
Click Relationship button from top toolbar
Select the required FK relations (one by one)
Right Side - Expand INSERT or UPDATE Specification
Change the UPDATE Rule to - Cascade
Close and Save, Done!
(Tried on SQL 2008)
As I'm not too confident disabling FK constraints, I prefer too :
Duplicate the row with the old PK with one with the new PK
Update the FKs
Delete the row with the old PK
Advantage : No constraint violated during the process.
Go to foreign Key Relations of each child tables and on Insert and Update specification change delete and update rules to cascade.
create a New row with the same data and a different primary key.
update all the children tables.
remove the row that you repeated its data
And its done.

Resources