How to update same columns on different tables at the same time? - sql

I have Table-A with a column called serial_number, and Table-B has the same column.
Update a single table is not possible to their linkage, upon attempt though, this is the error:
The UPDATE statement conflicted with the FOREIGN KEY constraint
"L_231". The conflict occurred in
database "Main", table "dbo.Products".
The statement has been terminated.
I know how I can delete the field in both in case I need to, I just don't know how to update it simultaneously.
Thanks.

this is a BAD design. if this isn't a "one time thing" to fix an issue, but part of your applicaion, you need a redesign.
You shouldn't update keys, use a surrogate key (like an identity) instead and then store the serial_number as a plain data column (which can be easily changed).

You should be able to set the constraint as ON UPDATE CASCADE.

Hello
Good question but ????
one Method is Update trigger
you update in same time on different table

Related

The INSERT statement conflicted with the FOREIGN KEY constraint__ [duplicate]

I am getting the following error. Could you please help me?
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Sup_Item_Sup_Item_Cat". The conflict occurred in database "dev_bo", table "dbo.Sup_Item_Cat". The statement has been terminated.
Code:
insert into sup_item (supplier_id, sup_item_id, name, sup_item_cat_id,
status_code, last_modified_user_id, last_modified_timestamp, client_id)
values (10162425, 10, 'jaiso', '123123',
'a', '12', '2010-12-12', '1062425')
The last column client_id is causing the error. I tried to put the value which already exists in the dbo.Sup_Item_Cat into the column, corresponding to the sup_item.. but no joy :-(
In your table dbo.Sup_Item_Cat, it has a foreign key reference to another table. The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table.
If you have SQL Server Management Studio, open it up and sp_help 'dbo.Sup_Item_Cat'. See which column that FK is on, and which column of which table it references. You're inserting some bad data.
Let me know if you need anything explained better!
I had this issue myself, regarding the error message that is received trying to populate a foreign key field. I ended up on this page in hopes of finding the answer. The checked answer on this page is indeed the correct one, unfortunately I feel that the answer is a bit incomplete for people not as familiar with SQL. I am fairly apt at writing code but SQL queries are new to me as well as building database tables.
Despite the checked answer being correct:
Mike M wrote-
"The way a FK works is it cannot have a value in that column that is
not also in the primary key column of the referenced table."
What is missing from this answer is simply;
You must build the table containing the Primary Key first.
Another way to say it is;
You must Insert Data into the parent table, containing the Primary
Key, before attempting to insert data into the child table containing
the Foreign Key.
In short, many of the tutorials seem to be glazing over this fact so that if you were to try on your own and didn't realize there was an order of operations, then you would get this error. Naturally after adding the primary key data, your foreign key data in the child table must conform to the primary key field in the parent table, otherwise, you will still get this error.
If anyone read down this far. I hope this helped make the checked answer more clear. I know there are some of you who may feel that this sort of thing is pretty straight-forward and that opening a book would have answered this question before it was posted, but the truth is that not everyone learns in the same way.
You are trying to insert a record with a value in the foreign key column that doesn't exist in the foreign table.
For example: If you have Books and Authors tables where Books has a foreign key constraint on the Authors table and you try to insert a book record for which there is no author record.
You'll need to post your statement for more clarification. But...
That error means that the table you are inserting data into has a foreign key relationship with another table. Before data can be inserted, the value in the foreign key field must exist in the other table first.
The problem is not with client_id from what I can see. It looks more like the problem is with the 4th column, sup_item_cat_id
I would run
sp_helpconstraint sup_item
and pay attention to the constraint_keys column returned for the foreign key FK_Sup_Item_Sup_Item_Cat to confirm which column is the actual problem, but I am pretty sure it is not the one you are trying to fix. Besides '123123' looks suspect as well.
Something I found was that all the fields have to match EXACTLY.
For example, sending 'cat dog' is not the same as sending 'catdog'.
What I did to troubleshoot this was to script out the FK code from the table I was inserting data into, take note of the "Foreign Key" that had the constraints (in my case there were 2) and make sure those 2 fields values matched EXACTLY as they were in the table that was throwing the FK Constraint error.
Once I fixed the 2 fields giving my problems, life was good!
If you need a better explanation, let me know.
I ran into this problem when my insert value fields contained tabs and spaces that were not obvious to the naked eye. I had created my value list in Excel, copied, and pasted it to SQL, and run queries to find non-matches on my FK fields.
The match queries did not detect there were tabs and spaces in my FK field, but the INSERT did recognize them and it continued to generate the error.
I tested again by copying the content of the FK field in one record and pasting it into the insert query. When that record also failed, I looked closer at the data and finally detected the tabs/spaces.
Once I cleaned removed tabs/spaces, my issue was resolved. Hope this helps someone!
Double check the fields in the relationship the foreign key is defined for. SQL Server Management Studio may not have had the fields you wanted selected when you defined the relationship. This has burned me in the past.
run sp_helpconstraint
pay ATTENTION to the constraint_keys column returned for the foreign key
I had the same problem when I used code-first migrations to build my database for an MVC 5 application. I eventually found the seed method in my configuration.cs file to be causing the issue. My seed method was creating a table entry for the table containing the foreign key before creating the entry with the matching primary key.
Parent table data missing causes the problem.
In your problem non availability of data in "dbo.Sup_Item_Cat" causes the problem
I also got the same error in my SQL Code, This solution works for me,
Check the data in Primary Table May be you are entering a column value which is not present in the primary key column.
The problem was reproducible and intermittent for me using mybatis.
I'm sure I had correct DB configuration (PK, FK, auto increment etc)
I'm sure I had correct order of insertions (parent records first), in debug I could see parent record inserted with respective PK and just after that next statement failed with inserting child record with correct FK inside.
The problem was fixed by for reseeding identity with
DBCC CHECKIDENT ('schema.customer', RESEED, 0);
DBCC CHECKIDENT ('schema.account', RESEED, 0);
Exactly the same code that failed before started to work.
I would like somebody to explain me what was causing the issue.
In my case, I was inserting the values into the child table in the wrong order:
For the table with 2 columns: column1 and column2, I got this error when I mistakenly entered:
INSERT INTO Table VALUES('column2_value', 'column1_value');
The error was resolved when I used the below format:-
INSERT INTO Table (column2, column1) VALUES('column2_value', 'column1_value');
If your FK column table should contain that FK value as a primary key Value then data will be inserted.

MSSQL Multiple FKs in table: cannot have multiple cascade/set nulls?

I have a fairly simple design, as follows:
What I want to achieve in my grouping_individual_history is marked in red:
when a session is deleted, I want to cascade delete the grouping_history....
when a grouping is deleted, I just want the child field to be nullified
It seems that MSSQL will not allow me to have more than one FK that does something else than no action ... It'll complain with:
Introducing FOREIGN KEY constraint 'FK_grouping_individual_history_grouping' on table 'grouping_individual_history' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I've already read this post (https://www.mssqltips.com/sqlservertip/2733/solving-the-sql-server-multiple-cascade-path-issue-with-a-trigger/), although it's not quite the same scenario it seems to me.
I've tried doing a INSTEAD OF DELETE trigger on my grouping table, but it wont accept it, because in turn, my grouping table has another FK (fkSessionID) that does a cascade delete... So, the fix would be to change it all, in all affected tables with FKs. The chain is long though, and we cannot consider it.
For one thing, can someone explain to me why SQL Server is giving me the issue for this very simple scenario in the first place? I just don't understand it.
Is there another workaround I could use (besides just removing the foreign key link from my grouping_individual_history table)?

Create foreign key without checking existing data

This is a 2 part question.
Question 1: I am trying to create a foreign key on a table where I need to turn off the "Check Existing Data on Creation or Re-Enabling". I know theres an option visually but I'm looking for a way to do it programmatically. Is there anyway to do this?
Question 2: I have a code table and two tables A and B that need to reference that code table. I want to have these both referenced from a relationship table but I want to able to use the same column. Can I have 2 foreign keys pointing to the same column?
Yes you can have the same column inthe parent table refer to differnt columns in multiple tables.
I do not recommend turning off checking FK on creation. If you have bad data now, you need to fix it now. Otherwise the first time someone edits one of those records it will fail the FK check then.
From Books online as to why it is a bad idea to use nocheck:
If you do not want to verify new CHECK
or FOREIGN KEY constraints against
existing data, use WITH NOCHECK. We do
not recommend doing this, except in
rare cases. The new constraint will be
evaluated in all later data updates.
Any constraint violations that are
suppressed by WITH NOCHECK when the
constraint is added may cause future
updates to fail if they update rows
with data that does not comply with
the constraint.

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

I am getting the following error. Could you please help me?
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Sup_Item_Sup_Item_Cat". The conflict occurred in database "dev_bo", table "dbo.Sup_Item_Cat". The statement has been terminated.
Code:
insert into sup_item (supplier_id, sup_item_id, name, sup_item_cat_id,
status_code, last_modified_user_id, last_modified_timestamp, client_id)
values (10162425, 10, 'jaiso', '123123',
'a', '12', '2010-12-12', '1062425')
The last column client_id is causing the error. I tried to put the value which already exists in the dbo.Sup_Item_Cat into the column, corresponding to the sup_item.. but no joy :-(
In your table dbo.Sup_Item_Cat, it has a foreign key reference to another table. The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table.
If you have SQL Server Management Studio, open it up and sp_help 'dbo.Sup_Item_Cat'. See which column that FK is on, and which column of which table it references. You're inserting some bad data.
Let me know if you need anything explained better!
I had this issue myself, regarding the error message that is received trying to populate a foreign key field. I ended up on this page in hopes of finding the answer. The checked answer on this page is indeed the correct one, unfortunately I feel that the answer is a bit incomplete for people not as familiar with SQL. I am fairly apt at writing code but SQL queries are new to me as well as building database tables.
Despite the checked answer being correct:
Mike M wrote-
"The way a FK works is it cannot have a value in that column that is
not also in the primary key column of the referenced table."
What is missing from this answer is simply;
You must build the table containing the Primary Key first.
Another way to say it is;
You must Insert Data into the parent table, containing the Primary
Key, before attempting to insert data into the child table containing
the Foreign Key.
In short, many of the tutorials seem to be glazing over this fact so that if you were to try on your own and didn't realize there was an order of operations, then you would get this error. Naturally after adding the primary key data, your foreign key data in the child table must conform to the primary key field in the parent table, otherwise, you will still get this error.
If anyone read down this far. I hope this helped make the checked answer more clear. I know there are some of you who may feel that this sort of thing is pretty straight-forward and that opening a book would have answered this question before it was posted, but the truth is that not everyone learns in the same way.
You are trying to insert a record with a value in the foreign key column that doesn't exist in the foreign table.
For example: If you have Books and Authors tables where Books has a foreign key constraint on the Authors table and you try to insert a book record for which there is no author record.
You'll need to post your statement for more clarification. But...
That error means that the table you are inserting data into has a foreign key relationship with another table. Before data can be inserted, the value in the foreign key field must exist in the other table first.
The problem is not with client_id from what I can see. It looks more like the problem is with the 4th column, sup_item_cat_id
I would run
sp_helpconstraint sup_item
and pay attention to the constraint_keys column returned for the foreign key FK_Sup_Item_Sup_Item_Cat to confirm which column is the actual problem, but I am pretty sure it is not the one you are trying to fix. Besides '123123' looks suspect as well.
Something I found was that all the fields have to match EXACTLY.
For example, sending 'cat dog' is not the same as sending 'catdog'.
What I did to troubleshoot this was to script out the FK code from the table I was inserting data into, take note of the "Foreign Key" that had the constraints (in my case there were 2) and make sure those 2 fields values matched EXACTLY as they were in the table that was throwing the FK Constraint error.
Once I fixed the 2 fields giving my problems, life was good!
If you need a better explanation, let me know.
I ran into this problem when my insert value fields contained tabs and spaces that were not obvious to the naked eye. I had created my value list in Excel, copied, and pasted it to SQL, and run queries to find non-matches on my FK fields.
The match queries did not detect there were tabs and spaces in my FK field, but the INSERT did recognize them and it continued to generate the error.
I tested again by copying the content of the FK field in one record and pasting it into the insert query. When that record also failed, I looked closer at the data and finally detected the tabs/spaces.
Once I cleaned removed tabs/spaces, my issue was resolved. Hope this helps someone!
Double check the fields in the relationship the foreign key is defined for. SQL Server Management Studio may not have had the fields you wanted selected when you defined the relationship. This has burned me in the past.
run sp_helpconstraint
pay ATTENTION to the constraint_keys column returned for the foreign key
I had the same problem when I used code-first migrations to build my database for an MVC 5 application. I eventually found the seed method in my configuration.cs file to be causing the issue. My seed method was creating a table entry for the table containing the foreign key before creating the entry with the matching primary key.
Parent table data missing causes the problem.
In your problem non availability of data in "dbo.Sup_Item_Cat" causes the problem
I also got the same error in my SQL Code, This solution works for me,
Check the data in Primary Table May be you are entering a column value which is not present in the primary key column.
The problem was reproducible and intermittent for me using mybatis.
I'm sure I had correct DB configuration (PK, FK, auto increment etc)
I'm sure I had correct order of insertions (parent records first), in debug I could see parent record inserted with respective PK and just after that next statement failed with inserting child record with correct FK inside.
The problem was fixed by for reseeding identity with
DBCC CHECKIDENT ('schema.customer', RESEED, 0);
DBCC CHECKIDENT ('schema.account', RESEED, 0);
Exactly the same code that failed before started to work.
I would like somebody to explain me what was causing the issue.
In my case, I was inserting the values into the child table in the wrong order:
For the table with 2 columns: column1 and column2, I got this error when I mistakenly entered:
INSERT INTO Table VALUES('column2_value', 'column1_value');
The error was resolved when I used the below format:-
INSERT INTO Table (column2, column1) VALUES('column2_value', 'column1_value');
If your FK column table should contain that FK value as a primary key Value then data will be inserted.

When to use "ON UPDATE CASCADE"

I use ON DELETE CASCADE regularly but I never use ON UPDATE CASCADE as I am not so sure in what situation it will be useful.
For the sake of discussion let see some code.
CREATE TABLE parent (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
);
CREATE TABLE child (
id INT NOT NULL AUTO_INCREMENT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id)
REFERENCES parent(id)
ON DELETE CASCADE
);
For ON DELETE CASCADE, if a parent with an id is deleted, a record in child with parent_id = parent.id will be automatically deleted. This should be no problem.
This means that ON UPDATE CASCADE will do the same thing when id of the parent is updated?
If (1) is true, it means that there is no need to use ON UPDATE CASCADE if parent.id is not updatable (or will never be updated) like when it is AUTO_INCREMENT or always set to be TIMESTAMP. Is that right?
If (2) is not true, in what other kind of situation should we use ON UPDATE CASCADE?
What if I (for some reason) update the child.parent_id to be something not existing, will it then be automatically deleted?
Well, I know, some of the question above can be test programmatically to understand but I want also know if any of this is database vendor dependent or not.
Please shed some light.
It's true that if your primary key is just an identity value auto incremented, you would have no real use for ON UPDATE CASCADE.
However, let's say that your primary key is a 10 digit UPC bar code and because of expansion, you need to change it to a 13-digit UPC bar code. In that case, ON UPDATE CASCADE would allow you to change the primary key value and any tables that have foreign key references to the value will be changed accordingly.
In reference to #4, if you change the child ID to something that doesn't exist in the parent table (and you have referential integrity), you should get a foreign key error.
Yes, it means that for example if you do UPDATE parent SET id = 20 WHERE id = 10 all children parent_id's of 10 will also be updated to 20
If you don't update the field the foreign key refers to, this setting is not needed
Can't think of any other use.
You can't do that as the foreign key constraint would fail.
I think you've pretty much nailed the points!
If you follow database design best practices and your primary key is never updatable (which I think should always be the case anyway), then you never really need the ON UPDATE CASCADE clause.
Zed made a good point, that if you use a natural key (e.g. a regular field from your database table) as your primary key, then there might be certain situations where you need to update your primary keys. Another recent example would be the ISBN (International Standard Book Numbers) which changed from 10 to 13 digits+characters not too long ago.
This is not the case if you choose to use surrogate (e.g. artifically system-generated) keys as your primary key (which would be my preferred choice in all but the most rare occasions).
So in the end: if your primary key never changes, then you never need the ON UPDATE CASCADE clause.
Marc
A few days ago I've had an issue with triggers, and I've figured out that ON UPDATE CASCADE can be useful. Take a look at this example (PostgreSQL):
CREATE TABLE club
(
key SERIAL PRIMARY KEY,
name TEXT UNIQUE
);
CREATE TABLE band
(
key SERIAL PRIMARY KEY,
name TEXT UNIQUE
);
CREATE TABLE concert
(
key SERIAL PRIMARY KEY,
club_name TEXT REFERENCES club(name) ON UPDATE CASCADE,
band_name TEXT REFERENCES band(name) ON UPDATE CASCADE,
concert_date DATE
);
In my issue, I had to define some additional operations (trigger) for updating the concert's table. Those operations had to modify club_name and band_name. I was unable to do it, because of reference. I couldn't modify concert and then deal with club and band tables. I couldn't also do it the other way. ON UPDATE CASCADE was the key to solve the problem.
The ON UPDATE and ON DELETE specify which action will execute when a row in the parent table is updated and deleted. The following are permitted actions : NO ACTION, CASCADE, SET NULL, and SET DEFAULT.
Delete actions of rows in the parent table
If you delete one or more rows in the parent table, you can set one of the following actions:
ON DELETE NO ACTION: SQL Server raises an error and rolls back the delete action on the row in the parent table.
ON DELETE CASCADE: SQL Server deletes the rows in the child table that is corresponding to the row deleted from the parent table.
ON DELETE SET NULL: SQL Server sets the rows in the child table to NULL if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must be nullable.
ON DELETE SET DEFAULT: SQL Server sets the rows in the child table to their default values if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must have default definitions. Note that a nullable column has a default value of NULL if no default value specified.
By default, SQL Server appliesON DELETE NO ACTION if you don’t explicitly specify any action.
Update action of rows in the parent table
If you update one or more rows in the parent table, you can set one of the following actions:
ON UPDATE NO ACTION: SQL Server raises an error and rolls back the update action on the row in the parent table.
ON UPDATE CASCADE: SQL Server updates the corresponding rows in the child table when the rows in the parent table are updated.
ON UPDATE SET NULL: SQL Server sets the rows in the child table to NULL when the corresponding row in the parent table is updated. Note that the foreign key columns must be nullable for this action to execute.
ON UPDATE SET DEFAULT: SQL Server sets the default values for the rows in the child table that have the corresponding rows in the parent table updated.
FOREIGN KEY (foreign_key_columns)
REFERENCES parent_table(parent_key_columns)
ON UPDATE <action>
ON DELETE <action>;
See the reference tutorial.
It's an excellent question, I had the same question yesterday. I thought about this problem, specifically SEARCHED if existed something like "ON UPDATE CASCADE" and fortunately the designers of SQL had also thought about that. I agree with Ted.strauss, and I also commented Noran's case.
When did I use it? Like Ted pointed out, when you are treating several databases at one time, and the modification in one of them, in one table, has any kind of reproduction in what Ted calls "satellite database", can't be kept with the very original ID, and for any reason you have to create a new one, in case you can't update the data on the old one (for example due to permissions, or in case you are searching for fastness in a case that is so ephemeral that doesn't deserve the absolute and utter respect for the total rules of normalization, simply because will be a very short-lived utility)
So, I agree in two points:
(A.) Yes, in many times a better design can avoid it; BUT
(B.) In cases of migrations, replicating databases, or solving emergencies, it's a GREAT TOOL that fortunately was there when I went to search if it existed.
My comment is mainly in reference to point #3: under what circumstances is ON UPDATE CASCADE applicable if we're assuming that the parent key is not updateable? Here is one case.
I am dealing with a replication scenario in which multiple satellite databases need to be merged with a master. Each satellite is generating data on the same tables, so merging of the tables to the master leads to violations of the uniqueness constraint. I'm trying to use ON UPDATE CASCADE as part of a solution in which I re-increment the keys during each merge. ON UPDATE CASCADE should simplify this process by automating part of the process.
To add to other great answers here it is important to use ON UPDATE CASCADE (or on DELETE CASCADE...) cautiously. Operations on tables with this specification require exclusive lock on underlaying relations.
If you have multiple CASCADE definitions in one table (as in other answer), and especially multiple tables using same definitions, and multiple users updating, this can create a deadlock when one process acquires exclusive lock on first underlaying table, other exclusive lock on second, and they block out each other by none of them being able to get both (all) exclusive locks to perform operation.