Alter composite key to include newly added column in sql server 2005 - sql

I have a table GB_Assignor_Assignee. I have a primary key which includes this combination(StateCode, CountyID, Doc_Type_Group_Code). Now i have to add a new column Doc_Type_Code. I added it by altering table. I want to include this new column inside this primary key.So my combination will be(StateCode, CountyID, Doc_Type_Group_Code,Doc_Type_Code).
How can i alter this primary key to add new column. I donot want to drop it and then recreate it. Please suggest.

If you want to change the primary key to include a new column, you have to drop and recreate it - there's no other way. You cannot add a column to an existing primary key after it's been created.
The question is: wouldn't you be better off creating a new artificial ID (of type INT) as your PK? You wouldn't have to change it if yet another column comes along, referencing the table will be MUCH easier (JOIN on just a single INT instead of five or six columns)......

You have to drop and recreate your PK.
This involves dropping any foreign keys that reference it. This should be obvious in any case as the foreign keys would also have to change to reflect the new column. (Hopefully not many in the case of composite PKs).
Drop the PK itself.
Create the new PK with the additional column.
Recreate all foreign keys.
The easiest way to do this is to make the change in SQL Server's table designer, and ask it to generate the change script for you.

Related

Query to Alter Primary Key to any column with keyword

I have a database with several tables that I am looking to add primary keys to any column with the keyword "KEY" in its name. The first problem that doesn't seem fixable is to run a query against all tables rather than one by one... Secondly I don't see how I can Add Primary key or even drop constraints on wildcard column searches.
For those of you who are visual, this is what I am trying to achieve:
ALTER TABLE *
ADD PRIMARY KEY (%KEY%);
Keeping in mind SOME tables already have Primary Keys attached, so I may need to Drop Constraints on all first then re-constrain them. If even possible?
If you want to define existing autonumber fields as primary key, consider:
ALTER TABLE tablename ADD CONSTRAINT fieldname PRIMARY KEY(fieldname)
However, field cannot already be set with an index and table cannot already have a primary key. Again, use ALTER TABLE to remove index.
ALTER TABLE tablename DROP CONSTRAINT indexname
Will have to run this SQL for each table that must be modified. If this is a one-time only requirement (why would it not be?), probably just as fast to open each table and manually modify design.
MS documentation https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/alter-table-statement-microsoft-access-sql
The alternative is VBA using TableDefs to modify table structure. Search web for examples.

Moving primary key from int to Guid

In my current project, I have to sync multiple client databases to one server database. I had given a try with Microsoft's sync framework and is not useful in my case. Therefor I have to do sync manually. for that I need to change primary key constraints from int to guid in all the tables.
Problem is this primary keys are also referred as foreign key in other tables.
I had referred below,
Moving from ints to GUIDs as primary keys
I am not good at SQL. I understood the logic but actual implementation is very tough for me.
ALTER TABLE MyTable
ADD GuidCol NVARCHAR(50) NOT NULL,
CONSTRAINT AK_GuidCol UNIQUE(GuidCol)
in above code I tried to add a column GuidCol as unique column after googling a lot. But
I don't know How can I fill values in the newly created column?
How can I make this column as PK after assigning value(s)?
How to make sure that this process won't break existing foreign key constraints?
I don't know How can I fill values in the newly created column?
The link you provided gives a solution:
Create a new column for the guid value in the master table. Use the
uniqueidentifier data type, make it not null with a newid()
default so all existing rows will be populated.
So your code should look like this:
alter table myTable add GuidCol uniqueidentifier not null default newid()
How can I make this column as PK after assigning value(s)? How to
make sure that this process won't break existing foreign key
constraints?
The same answer tells you:
Create new uniqueidentifier columns in the child tables.
Run update statements to build the guild relationships using the
exisitng int relationships to reference the entities.
Drop the original int columns.
Use the same uniqueidentifier type as in previuos statement, but instead of providing defalut, run the update statements joining the tables on existing integer id and set in the child's column the corresponding parent value.
Now you have child-parent relationship established but without constraints on them. Drop int columns and create PK and FK on new guid columns

Multiple foreign keys and multiple constrains

Let's assume I have a table called boxes with the box_id attribute as the PK.
There are two other tables. The first one is red_boxes and the second blue_boxes.
I have added a constraint to the red_boxes table
ALTER TABLE red_boxes
ADD CONSTRAINT fk_box_id
FOREIGN KEY (box_id)
REFERENCES boxes (box_id);
Now, I would like to add a constraint to the blue_boxes table. The SQL structure would look like the following, if I did not add the constraint already to the the red_boxes. The obvious way to fix this is to name a new constraint differently e.g. fk_box_id2, but is this is a good way? Am I supposed to somehow re-use the previous constraint, or this is not possible, why?
ALTER TABLE blue_boxes
ADD CONSTRAINT fk_box_id
FOREIGN KEY (box_id)
REFERENCES boxes (box_id)
Each constraint is separate and requires a unique name. My recommendation is to use the source and destination table names, for example fk_red_boxes_boxes and fk_blue_boxes_boxes. This way you can easily identify where they come from and where they go to.
If you have underscores in your table names, you might want to come up with a modified convention that you can easily understand at a glance. For example, a double underscore: fk__blue_boxes__boxes and fk__red_boxes__boxes.

adding a foreign key constraint to a primary key column of a table with existing data

I'm trying to add in a foreign key constraint on a newly created column of an existing table(table A) and the primary key column of a newly created table (table B). This is on sql server 2008. When I add in the relationship the Alter table script fails. I have also made the new column created on table A to allow nulls.
However when I try to save with NO on Check Existing data - I'm able to save the relationship.
Is this a good way of creating foreign key constraint on existing data, or should I create a new table (table c) mimicking a many to many relationship instead of adding the new column to table A,which will enable me to create my foreign key constraints without having to specify "No Check" on existing data, although the actual relationship is one to many.
Yes, you can do that by making Checking Existing Data On Creation Or Re-Enabling = No
If you do not want to verify new CHECK or FOREIGN KEY constraints against existing data, use WITH NOCHECK

How can I replace the existing primary key with a new primary key on my table?

I'm working with a legacy SQL Server database which has a core table with a bad primary key.
The key is of type NVARCHAR(50) and contains an application-generated string based on various things in the table. For obvious reasons, I'd like to replace this key with an auto-incrementing (identity) INT column.
This is a huge database and we're upgrading it piece-by-piece. We want to minimize the changes to tables that other components write to. I figured I could change the table without breaking anything by just:
Adding the new Id column to the table and making it nullable
Filling it with unique integers and making it NOT NULL
Dropping the existing primary key while ensuring there's a uniqueness constraint still on that column
Setting the new Id column to be the new primary key and identity
Item 3 is proving very painful. Because this is a core table, there are a lot of other tables with foreign key constraints on it. To drop the existing primary key, it seems I have to delete all these foreign key constraints and create them again afterwards.
Is there an easier way to do this or will I just have to script everything?
Afraid that is the bad news. We just got through a big project of doing the same type of thing, although our head DBA had a few tricks up his sleeve. You might look at something like this to get your scripts generated for the flipping of the switch:
I once did the same thing and basically used the process you describe. Except of course you have to first visit each other table and add new foreign key pointing to the new column in your base table
So the approach I used was
Add a new column with an auto incrementing integer in the base table, ensure it has a unique index on it (to be replaced later by the primary key)
For each foreign key relationship pointing to the base table add a new column in the child table. (note this can result in adding more than one column in the child table if more than one relationship)
For each instance of a key in the child table enter a value into the new foreign key field(s)
Replace your foreign key relationships such that the new column now serves
Make the new column in the base table the primary
Drop the old primary key in the base table and each old foreign key in the
children.
It is doable and not as hard as it might sound at first. The crux is a series of update statements for the children table of the nature
Update child_table
set new_column = (select new_primary from base)
where old_primary = old_foreign