Update table primary key and propagate changes to other tables - sql-server

I have Table A with Column A1Id as primary key, Column A1 and Column A2.
I have Table B with Column A1Id as foreign key, Column B1, and Column B2.
I have Table C with Column AI1d as foreign key, Column C1, and Column C2.
How can i update all the columns with a single command?
How can i propagate changes to all foreign keys if i update the primary key?
I'm new to SQL is this a trivial task?
I'm currently having difficulty updating a single table because of the foreign key constraint.

How can i update all the columns with a single command?
How can i propagate changes to all foreign keys if i update the primary key?
is this a trivial task?
You can't do this with a single command, it is not a trivial task, it typically takes a script of sql commands with the changes repeated for each table; usually involving UPDATEs and new columns to "migrate" the old data to the new format. Changing primary keys is something that is done very infrequently, and is almost always considered a major change even when the specifics of that change are fairly minor.
The closest (physical) analogy I can think of offhand is trying to take something apart and replace all it's screws with bolts.
Edit: If you are just talking about changing the values, not the fields or data type of the values, used as primary keys; then R VISHAL's answer is pointing in the right direction. You'll need to drop all your current constraints and recreate them to cascade the updates. You can also disable foreign key checks, change the values and then re-enable foreign key checks; but that is generally not recommended as re-enabling them does not recheck them, so if your updates put the data in an inconsistent state, it will not be corrected or even detected; and the setting is global, so any other activity going on will also be free to ignore their own fk constraints.
... but you shouldn't typically be changing primary key values either. If the value changes, it probably isn't a good candidate for a foreign key; and if it is a synthetic value (like an auto-incremented id) then you should almost never be changing it (many newer users are tempted to try to "condense" them when holes appear, but it is seldom a good idea.)

If, in your case, table B(A1id) and table C(A1id) both reference table A(A1id), then to propagate either update or delete operations to all foreign keys of tables B,C they should have the CASCADE constraint in them. In MySQL, for example, you could do this:
ALTER TABLE B
ADD CONSTRAINT FKA
FOREIGN KEY B(A1id)
REFERENCES A(A1id)
ON UPDATE CASCADE
ON DELETE CASCADE
Notice the word cascade. Is this what u want or am I missing something here? :/

Related

Circular foreign keys in PostgreSQL

I'm having a bit of an issue with circular foreign keys. I have a table posts with a uid column that is a BIGINT NOT NULL PRIMARY KEY, and I need to reference that in the last_seen_post column of my users table. The problem is that there's a sender_id column in posts that references users(user_id), meaning that I can't use both foreign keys at the same time because depending on the order of table definition, one of them will not be defined. Any fixes other than to drop the foreign key on the last_seen_post column?
I really would rather avoid dropping either foreign keys because the data integrity for this backend is mission critical. I know I could probably make another table to achieve this, but I was really hoping to get away with this since it's way cheaper in terms of space and search time
For context, the last_seen_post column is supposed to help the backend figure out what the user's "feed" is, i.e. the collection of posts from users they follow that they have not downloaded yet.
Alright, I figured it out, so I'm gonna leave the solution here if others need it in the future. The easiest thing to do is to create the column without the foreign key constraint and then do ALTER TABLE yourtbl ADD FOREIGN KEY (yourcolumn) REFERENCES othertbl(othercolumn); once both tables have been created!

SQL Server : setting foreign key to a specific value

I'm not sure what is the best way to structure my question.
I have a table with foreign key column in it. By default the foreign key is set to NOT NULL and I want to keep it that way for now, because maybe this will be the final result. But for now there could be records that don't need (and have) foreign keys values and I want to distinct them somehow so it is as clear as possible that these records are something different from the other.
I tried but as it seems I can not use negative numbers for bigint which is the value of the foreign key in my SQL Server table. I guess this is pretty standard stuff so what is the best thing to do in this situation besides making the foreign key to NULL?
Not sure why HABO didn't make that the answer, because that's pretty much your only option.
Make it NULL
Create a row in the referenced table and set it to TBD or whatever moniker you prefer and use the ID from that instead of NULL
If you have records that do not need an FK and never will, then you should set the column to NULL, else use a temp value.
You cannot use a negative value because you MUST reference something in the foreign table if you have a foreign key constraint.
Foreign key constraints enforces you to refer an existing PK of the other table.
One way not mentioned yet is to drop the constraint for now :
ALTER TABLE YourTable
DROP CONSTRAINT fk_something

Handle primary key - foreign key tables insertion?

Suppose I have two tables (primary key -> foreign key) where one record in primary key table corresponds to many record in foreign key, so if I want to make insert page (using ASP.NET for instance) for both primary key table and foreign key table, how can I get the primary key value to insert it into the foreign key table?
(usually I took the max(of PK) but I am curious to find better solution)
I assume you are using SQL Server, since you mention the use of ASP.NET. Using Max(PK) is not a good idea in a multi-user system because eventually you will end up getting an incorrect primary key value. There are also resource issues to consider. In general, this approach should be avoided.
There are several ways you can accomplish what you want to do. One way is to do your inserts via stored procedures. The stored procedure for creating the primary key row would return the Id value of the new row, which then can be used for inserting your foreign key rows. But don't use Max(PK Value). Use the SCOPE_IDENTITY() value. This assumes you are using an Identity type for your PK values. You don't state what you are actually using.

MySQL Foreign keys: should i set it up?

Do i need to setting the foreign key for this situation ?
i'm weak in database design, especially in mysql.. may i know if i want to setting foreign keys for them, what should i setting for them ? in case if the people delete... all referral to people_id will delete together, is it possible to set while the table is too many ?
Thx for reply
Yes. Foreign key constraints enforce referential integrity, a key tenet of ensuring that your data is reliable and of high quality. Otherwise, your people_address table could reference a people_id value that doesn't exist in the people table, and would be an orphan. A foreign key constraint would prevent that from happening.
So, just do it. There's really no good reason not to.
Define foreign keys such as the following on the people_email table:
ALTER TABLE people_email ADD CONSTRAINT FOREIGN KEY (people_id) REFERENCES people (id) ON DELETE CASCADE;
This will mean that you cannot enter a record in people_email where the people_id in that table does not exist in people. Also, if you delete the parent row in people, the rows referencing it in people_email with get automatically deleted.
I personally prefer to manually delete all the rows from the child tables and not use cascade deletes though. It's a bit of extra app dev work, but it makes me feel safer and also allows me some control over locking and ensuring that queries are as efficient as possible.

Delete a table referenced by a foreign keys

What is the best way to delete a table referenced by a foreign keys?
Is the intended goal to orphan those records and never use the foreign key again? If so the method mentioned before about disabling the key is fine, otherwise you may want to instead delete the records referencing the table you want to delete first (or update the to point to a more appropriate record, or NULL if that makes sense in this case). I seem to be coming at this from a different direction than others, are you sure the foreign key is pointless, and if so why not just remove it? At some point someone wanted to constraint this behavior, before just disabling constraints I make sure I understand their purpose and have a good justification for bypassing those safeguards.
Remove the foreign key constraint and then delete the table once no-one is forced to recognize it. If the column in the second table (the one not being deleted) is not used elsewhere, then you should probably delete the whole column after removing the constraint.
You need to remove the constraint before you're allowed to delete the table referenced by it. SQL Server uses the following syntax:
ALTER TABLE <table_name> DROP FOREIGN KEY <foreignkey_name>
Keep in mind that the constraint exists on the table that references the one you want to delete so that's the table you should be altering.
Do NOT delete a table with foreign key constraints without considering the impact on the foreign key tables. Let me explain the impact of simply deleting the foreign key and then the table with an example.
Consider two tables - parts and orderdetails. There is a foreign key constraint that says a part must exist before it can be put into the orderdetails table. What is stored in the orderdetail table is the id for the part from the parts table, not the part name or description. Suppose you drop the foreign key and then drop the parts table. Now all the data in the orderdetail table is totally useless because you have no way of knowing what the part ordered was. This would include orders not yet shipped and orders that the customer might call and ask questions about. Further you now have no way to recreate that data except by restoring a backup (hope you have one).
Further suppose you want to drop the table and recreate it to make a change to the table. Then reload the information and put the foreign key back on. In this case you should probaly use alter table instead of drop and recreate but if you don't you may end up with id numbers that are not the same as they were originally and thus now the orders will reference the wrong ids. This can be done safely but you would have to do it very carefully and with a lot of thought as to the consequences.
by using On Delete Cascade

Resources