|
44 / 41 / 35 Регистрация: 27.02.2013 Сообщений: 284 |
|
08.12.2014, 18:19. Показов 3854. Ответов 13 Помогите новичку разобраться со следующим примером. У меня есть связанные между собой внеш ключами табл1, табл2, табл3. Если я обновляю запись в табл1, нужно, чтобы в табл2 и табл3 тоже происходили изменения. Но когда я в запросе использую инструкцию UPDATE, программа выдает ошибку The UPDATE statement conflicted with the REFERENCE constraint «fk7». The conflict occurred in database «project»…
0 |
cpp_developer Эксперт 20123 / 5690 / 1417 Регистрация: 09.04.2010 Сообщений: 22,546 Блог |
08.12.2014, 18:19 |
Ответы с готовыми решениями: Инструкция MERGE! Триггер с after update не работает, а с for update работает Инструкция Insert 13 |
1313 / 945 / 144 Регистрация: 17.01.2013 Сообщений: 2,348 |
|
09.12.2014, 07:24 |
|
Это вы добиваетесь, чтобы первичный ключ в справочнике был без разрывов в нумерации? Удачи…
0 |
44 / 41 / 35 Регистрация: 27.02.2013 Сообщений: 284 |
|
09.12.2014, 09:36 [ТС] |
|
Сообщение от cygapb-007 Это вы добиваетесь, чтобы первичный ключ в справочнике был без разрывов в нумерации нет. мне просто нужно изменить запись одновременно в нескольких таблицах. Неужели никто не может объяснить как или объяснить что это невозможно.
0 |
1449 / 1121 / 347 Регистрация: 11.04.2011 Сообщений: 2,621 |
|
09.12.2014, 10:15 |
|
Сообщение от Lar4ik нет. мне просто нужно изменить запись одновременно в нескольких таблицах. Вам ничто не мешает просто изменить записи в нескольких таблицах, но если вы видите ошибку «The UPDATE statement conflicted with the REFERENCE constraint «fk7». The conflict occurred in database «project»…», то это означает, что вы хотите не просто изменить запись, вы хотите изменить первичный ключ, на который ссылаются внешние ключи из других таблиц. Как правила, подобная операция не имеет смысла, но если сильно хочется, то можно создавать внешний ключ с аргументом ON UPDATE CASCADE.
0 |
44 / 41 / 35 Регистрация: 27.02.2013 Сообщений: 284 |
|
09.12.2014, 10:36 [ТС] |
|
Сообщение от kodv создавать внешний ключ с аргументом ON UPDATE CASCADE. он у меня и создан таким образом
0 |
1313 / 945 / 144 Регистрация: 17.01.2013 Сообщений: 2,348 |
|
09.12.2014, 12:53 |
|
Сообщение от Lar4ik программа выдает ошибку The UPDATE statement conflicted with the REFERENCE constraint «fk7». The conflict occurred in database «project»… Это срабатывает механизм защиты ссылочной целостности базы, и означает это (обычно), что в справочнике нет записи с указанным вами кодом.
0 |
44 / 41 / 35 Регистрация: 27.02.2013 Сообщений: 284 |
|
09.12.2014, 14:06 [ТС] |
|
Сообщение от cygapb-007 Это срабатывает механизм защиты ссылочной целостности базы, и означает это (обычно), что в справочнике нет записи с указанным вами кодом. так что мне теперь делать, удалить внешние ключи? просто вам людям знающим многие вещи очевидны. а я так и не поняла как мне решить мою задачу
0 |
1449 / 1121 / 347 Регистрация: 11.04.2011 Сообщений: 2,621 |
|
09.12.2014, 14:17 |
|
Сообщение от Lar4ik так что мне теперь делать не выполнять действия, нарушающие ссылочную целостность. Не нужно изменять значение из первичного ключа, если на него ссылаются внешние ключи. Не нужно внешнему ключу устанавливать значение, которое на момент выполнения команды отсутствует в родительской таблице. В каком месте вы нарушили ссылочную целостность, не ясно, так как вы не привели ни структуру таблиц ни выполняемый код.
0 |
Lar4ik 44 / 41 / 35 Регистрация: 27.02.2013 Сообщений: 284 |
||||
09.12.2014, 15:31 [ТС] |
||||
Миниатюры
0 |
1449 / 1121 / 347 Регистрация: 11.04.2011 Сообщений: 2,621 |
|
09.12.2014, 16:01 |
|
Lar4ik, у вас 2 внешних ключа ссылаются на изменяемое поле номер_катера. Оба ли ключа созданы с аргументом ON UPDATE CASCADE?
1 |
Lar4ik 44 / 41 / 35 Регистрация: 27.02.2013 Сообщений: 284 |
||||||||
09.12.2014, 16:13 [ТС] |
||||||||
Сообщение от kodv Оба ли ключа созданы с аргументом ON UPDATE CASCADE? да, оба
0 |
1449 / 1121 / 347 Регистрация: 11.04.2011 Сообщений: 2,621 |
|
09.12.2014, 16:43 |
|
Lar4ik, А почему у меня на почте вместо ON UPDATE CASCADE везде стоит ON DELETE CASCADE? Ответ, конечно, очевиден — редактирование сообщений не запрещено. Но от того, что вы изменили сообщение на форуме, ситуация в вашей БД не изменилась.
0 |
44 / 41 / 35 Регистрация: 27.02.2013 Сообщений: 284 |
|
09.12.2014, 16:54 [ТС] |
|
я еще раз пересоздала таблицы. все заработало. Добавлено через 9 минут
0 |
1449 / 1121 / 347 Регистрация: 11.04.2011 Сообщений: 2,621 |
|
09.12.2014, 17:00 |
|
Lar4ik, чтобы каскадом все обновлялось и удалялось нужно писать ON DELETE CASCADE ON UPDATE CASCADE
1 |
Новые блоги и статьи
Все статьи Все блоги / |
||||
Мульти-тенантные БД с PostgreSQL Row Security
Codd 23.04.2025 Современные облачные сервисы и бизнес-приложения всё чаще обслуживают множество клиентов в рамках единой программной инфраструктуры. Эта архитектурная модель, известная как мульти-тенантность, стала. . . |
Реализация конвейеров машинного обучения с Python и Scikit-learn
AI_Generated 23.04.2025 Мир данных вокруг нас растёт с каждым днём, и умение эффективно обрабатывать информацию стало необходимым навыком. Специалисты по машинному обучению ежедневно сталкиваются с задачами предобработки. . . |
Контроллеры Kubernetes Ingress: Сравнительный анализ
Mr. Docker 23.04.2025 В Kubernetes управление входящим трафиком представляет собой одну из ключевых задач при построении масштабируемых и отказоустойчивых приложений. Ingress — это API-объект, который служит вратами. . . |
Оптимизация кода Python с Cython и Numba
py-thonny 23.04.2025 Python прочно обосновался в топе языков программирования благодаря своей простоте и гибкости. Разработчики любят его за читабельность кода и богатую экосистему библиотек. Но у этой медали есть и. . . |
Микросервис на Python с FastAPI и Docker
ArchitectMsa 23.04.2025 В эпоху облачных вычислений и растущей сложности программных продуктов классическая монолитная архитектура всё чаще уступает место новым подходам. Микросервисная архитектура становится фаворитом. . . |
Создаем веб-приложение на Vue.js и Laravel
Reangularity 23.04.2025 Выбор правильного технологического стека определяет успех веб-проекта. Laravel и Vue. js формируют отличную комбинацию для создания современных приложений. Laravel — это PHP-фреймворк с элегантным. . . |
Максимальная производительность C#: Span<T> и Memory<T>
stackOverflow 22.04.2025 Мир высоконагруженных приложений безжалостен к неэффективному коду. Каждая миллисекунда на счету, каждый выделенный байт памяти может стать причиной падения производительности. Разработчики на C#. . . |
JWT аутентификация в Java
Javaican 21.04.2025 JWT (JSON Web Token) представляет собой открытый стандарт (RFC 7519), который определяет компактный и самодостаточный способ передачи информации между сторонами в виде JSON-объекта. Эта информация. . . |
Спринты Agile: Планирование, выполнение, ревью и ретроспектива
EggHead 21.04.2025 Спринты — сердцевина Agile-методологии, позволяющая командам создавать работающий продукт итерационно, с постоянной проверкой гипотез и адаптацией к изменениям. В основе концепции спринтов лежит. . . |
Очередные открытия мега простых чисел, сделанные добровольцами с помощью домашних компьютеров
Programma_Boinc 21.04.2025 Очередные открытия мега простых чисел, сделанные добровольцами с помощью домашних компьютеров. 3 марта 2025 года, в результате обобщенного поиска простых чисел Ферма в PrimeGrid был найден. . . |
Наверх
I have a table called patient_address
, which reference a PK key in patient
table. But if I try to run one of the following statements :
update patient set id_no='7008255601088' where id_no='8008255601089'
update patient_address set id_no='7008255601088' where id_no='8008255601089'
I get this error message:
«The UPDATE statement conflicted with the REFERENCE constraint
«FK__patient_a__id_no__27C3E46E». The conflict occurred in database
«PMS», table «dbo.patient_address», column ‘id_no’.» or «The
UPDATE statement conflicted with the FOREIGN KEY constraint
«FK__patient_a__id_no__27C3E46E». The conflict occurred in database
«PMS», table «dbo.patient», column ‘id_no’.» .
Does any body know the possible cause ? Thanks.
MackM
3,0245 gold badges35 silver badges48 bronze badges
asked May 25, 2014 at 14:39
chosenOne ThabschosenOne Thabs
1,6503 gold badges24 silver badges42 bronze badges
5
This error is encountered when the primary key of a table is updated but it is referenced by a foreign key from another table and the update specific is set to No action. The No action is the default option.
If this is your case and No action is set on the update operation you can change the foreign-key definition to Cascade.
Right click your foreign key and select Modify. In the Foreign key relationships dialog under the INSERT and UPDATE specifics set the UPDATE rule on Cascade:
You can also set the rule using T-SQL:
ALTER TABLE YourTable
DROP Constraint Your_FK
GO
ALTER TABLE YourTable
ADD CONSTRAINT [New_FK_Constraint]
FOREIGN KEY (YourColumn) REFERENCES ReferencedTable(YourColumn)
ON DELETE CASCADE ON UPDATE CASCADE
GO
Hope this helps
answered May 25, 2014 at 15:14
5
If you don’t want to change your table structure, you can run the following query:
ALTER TABLE [UserStore]
NOCHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT FK_UserIdentity_User_UserId
BEGIN TRAN
UPDATE [user]
SET Id = 10
WHERE Id = 9
UPDATE [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9
UPDATE [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9
COMMIT TRAN
ALTER TABLE [UserStore]
CHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE UserIdentity
CHECK CONSTRAINT FK_UserIdentity_User_UserId
answered Jul 11, 2019 at 21:12
Bartho BernsmannBartho Bernsmann
2,5131 gold badge28 silver badges34 bronze badges
1
It sometimes happens when you try to Insert/Update
an entity while the foreign key
that you are trying to Insert/Update
actually does not exist. So, be sure that the foreign key
exists and try again.
answered Feb 6, 2019 at 10:06
In MySQL
set foreign_key_checks=0;
UPDATE patient INNER JOIN patient_address
ON patient.id_no=patient_address.id_no
SET patient.id_no='8008255601088',
patient_address.id_no=patient.id_no
WHERE patient.id_no='7008255601088';
Note that foreign_key_checks only temporarily set foreign key checking false. So it need to execute every time before update statement. We set it 0 as if we update parent first then that will not be allowed as child may have already that value. And if we update child first then that will also be not allowed as parent may not have that value from which we are updating. So we need to set foreign key check.
Another thing is that if you are using command line tool to use this query then put care to mention spaces in place where i put new line or ENTER in code. As command line take it in one line, so it may happen that two words stick as patient_addressON which create syntax error.
answered Aug 6, 2016 at 3:41
This was the solution for me:
-- Check how it is now
select * from patient
select * from patient_address
-- Alter your DB
alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient
set id_no='7008255601088'
where id_no='8008255601088'
alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient_address
set id_no='7008255601088'
where id_no='8008255601088'
-- Check how it is now
select * from patient
select * from patient_address
answered Nov 8, 2018 at 23:28
Reason is as @MilicaMedic says. Alternative solution is disable all constraints, do the update and then enable the constraints again like this. Very useful when updating test data in test environments.
exec sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
update patient set id_no='7008255601088' where id_no='8008255601088'
update patient_address set id_no='7008255601088' where id_no='8008255601088'
exec sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
Source:
https://stackoverflow.com/a/161410/3850405
answered Apr 3, 2019 at 10:37
OgglasOgglas
70.6k42 gold badges380 silver badges474 bronze badges
I would not change the constraints,
instead, you can insert a new record in the table_1 with the primary key (id_no = 7008255601088). This is nothing but a duplicate row of the id_no = 8008255601088. so now patient_address with the foreign key constraint (id_no = 8008255601088) can be updated to point to the record with the new ID(ID which needed to be updated), which is updating the id_no to id_no =7008255601088.
Then you can remove the initial primary key row with id_no =7008255601088.
Three steps include:
- Insert duplicate row for new id_no
- Update Patient_address to point to new duplicate row
- Remove the row with old id_no
answered Jan 15, 2016 at 18:14
Charan RajCharan Raj
4815 silver badges8 bronze badges
I guess if you change the id_no
, some of the foreign keys would not reference anything, thus the constraint violation.
You could add initialy deffered
to the foreign keys, so the constraints are checked when the changes are commited
jezzah
911 silver badge9 bronze badges
answered May 25, 2014 at 14:45
wastlwastl
2,64115 silver badges27 bronze badges
3
Start asking to get answers
Find the answer to your question by asking.
Ask question
Explore related questions
See similar questions with these tags.
Symptoms
When you update the primary key column of the primary key table in Microsoft SQL Server 2005 by changing the case of the existing column values or by padding column values, you receive the following error message:
Msg 547, Level 16, State 0, Line 1
The UPDATE statement conflicted with the REFERENCE constraint «<Constraint>«. The conflict occurred in database «<Database name>«, table «<Table name>«, column ‘<Column name>‘.
For example, this problem occurs in both the following situations.
Example 1
-
You create two tables by using a case-insensitive collation such as the SQL_Latin1_General_CP1_CI_AS collation.
-
You build a primary key and foreign key relationship between these two tables.
-
You update the primary key column of the primary key table by changing the case of the existing column values.
Example 2
-
You create two tables.
-
You build a primary key and foreign key relationship between these two tables.
-
The ANSI_PADDING setting is set to OFF.
Note By default, the ANSI_PADDING setting is set to OFF.
-
You update the primary key column of the primary key table by padding the column values.
Cause
This problem occurs because values that are equal at the type level may be distinct at the binary level.
For example, at the type level, N’a’ is equal to N’A’. However, at the binary level, N’a’ is not equal to N’A’. The optimization mechanism incorrectly assumes that the update operation that changes the case does not make any real changes. Therefore, the PK-FK check is unsuccessful.
Resolution
Service pack information
To resolve this problem, obtain the latest service pack for SQL Server 2005. For more information, click the following article number to view the article in the Microsoft Knowledge Base:
913089 How to obtain the latest service pack for SQL Server 2005
Status
Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the «Applies to» section. This problem was first corrected in SQL Server 2005 Service Pack 3.
More Information
For more information about software update terminology, click the following article number to view the article in the Microsoft Knowledge Base:
824684 Description of the standard terminology that is used to describe Microsoft software updates
Need more help?
Want more options?
Explore subscription benefits, browse training courses, learn how to secure your device, and more.
Scenario:
You are working as SQL Server developer, You wrote an update statement for one of the table and getting below error.
Msg 547, Level 16, State 0, Line 32
The UPDATE statement conflicted with the REFERENCE constraint «FK_».
The conflict occurred in database «YourDatabaseName», table «SchemaName.YourTableName», column ‘ColumnName’.
The statement has been terminated.
How to resolve this issue?
Solution:
Let’s create this error first by using below script. We are going to create two tables dbo.Customer and dbo.Orders. The tables has Primary-Foreign Key Relationship.
USE YourDatabaseName GO CREATE TABLE dbo.Customer ( Customerid INT PRIMARY KEY ,FName VARCHAR(100) ,LName VARCHAR(100) ,SSN VARCHAR(10) ) CREATE TABLE dbo.Orders ( OrderId INT Identity(1, 1) ,OrderitemName VARCHAR(50) ,OrderItemAmt INT ,Customer_id INT FOREIGN KEY REFERENCES Customer(CustomerId) ) --insert sample data insert into dbo.Customer (CustomerId,FName, LName,SSN) values (1,'Aamir','Shahzad','000-000-00') insert into dbo.Orders (OrderItemName,OrderItemAmt,Customer_Id) values ('TV',1,1)
|
How to update record when Column is referenced by Foreign Key Constraint in SQL Server |
Now let’s say if you feel that CustomerId value is incorrect in dbo.Customer and need to be updated. You wrote below update statement to update CustomerId to 100.
update dbo.Customer set Customerid=100
You will get below error.
Msg 547, Level 16, State 0, Line 33
The UPDATE statement conflicted with the REFERENCE constraint «FK__Orders__Customer__1ED998B2».
The conflict occurred in database «YourDatabaseName», table «dbo.Orders», column ‘Customer_id’.
The statement has been terminated.
As there is no Customer_id value=100 in dbo.Orders table, You can’t update the record in reference table. Now you thought that let’s fix the Parent table first ( dbo.Orders) and then I can update the dbo.Customer table.
update dbo.Orders set Customer_Id=100
Again you got the error as shown below, because we don’t have CustomerId=100 available in dbo.Customer table.
Msg 547, Level 16, State 0, Line 36
The UPDATE statement conflicted with the FOREIGN KEY constraint «FK__Orders__Customer__1ED998B2».
The conflict occurred in database «YourDatabaseName», table «dbo.Customer», column ‘Customerid’.
The statement has been terminated.
From here we can come with with multiple solutions
1) Instead of updating the record, Insert the record in Reference Table ( Dbo.Customer), Then update the record in Parent table (Dbo.Orders) and finally delete the existing records from Reference Table.
--Insert Record in Reference Table First insert into dbo.Customer (CustomerId,FName, LName,SSN) values (100,'Aamir','Shahzad','000-000-00') --Update the Records in Parent Table update dbo.Orders set Customer_Id=100 --Delete the old record from Reference Table Delete from dbo.Customer where CustomerId=1
Check the records in table now.
|
How to update Column Value when referenced by Foreign Key Constraint in SQL Server |
2) Disable the Foreign Key Constraint and Update the Values Manually
Another solution can be, disable the Foreign Key constraint, update the records and finally enable the Foreign key again.
--Find the Foreign Key Constraint with Table Name USE YourDatabaseName GO Select Schema_name(Schema_id) as SchemaName, object_name(Parent_object_id) as TableName, name as ForeignKeyConstraintName from sys.foreign_keys
Disable the Foreign Key Constraint by using below statement
Syntax
ALTER TABLE SchemaName.ParentTableName
NOCHECK CONSTRAINT Constraint_Name
I used below statement to disable Foreign Key constraint on dbo.Orders table.
--Disable Foregin Key by using NOCHECK ALTER TABLE dbo.Orders NOCHECK CONSTRAINT FK__Orders__Customer__2A4B4B5E --Run Update Statements update dbo.Customer set Customerid=100 update dbo.Orders set Customer_Id=100
Enable Foreign Key Constraint Syntax
ALTER TABLE SchemaName.ParentTableName
CHECK CONSTRAINT Constraint_Name
I execute below script to Enable Foreign Key Constraint on dbo.Orders table.
--Enable Foreign Key Constraint by using CHECK ALTER TABLE dbo.Orders CHECK CONSTRAINT FK__Orders__Customer__2A4B4B5E
Video Demo : The UPDATE statement conflicted with the REFERENCE Constraint
Just replied on MSDN forum’s following post: http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/289c4ca5-6ab2-4ed6-b446-0300f5c7dc88
When tables are referenced by Foreign Key constraints it gets difficult to UPDATE the key columns.
An example shows this issue and how one can perform UPDATE on FK columns.
USE [tempdb] GO -- CREATE test tables CREATE TABLE dept (d_id INT PRIMARY KEY, dept VARCHAR(50)) CREATE TABLE emp (sn INT PRIMARY KEY, ename VARCHAR(50), d_fk INT CONSTRAINT fk_dept_d_fk FOREIGN KEY (d_fk) REFERENCES dept(d_id)) -- INSERT test data INSERT INTO dept SELECT 1, 'finance' UNION SELECT 2, 'hr' INSERT INTO emp SELECT 1, 'Manoj', 1 UNION SELECT 2, 'Saurabh', 2 UNION SELECT 3, 'Kanchan', 1 UNION SELECT 4, 'Pooja', 2 -- SELECT the INSERTed data SELECT * from dept
d_id dept
1 finance
2 hr -- DeptID needs to be updated to 3
SELECT * from emp
sn ename d_fk
1 Manoj 1
2 Saurabh 2 -- DeptID should also be updated here to 3
3 Kanchan 1
4 Pooja 2 -- DeptID should also be updated here to 3
-- Now lets UPDATE the FK column values UPDATE dept SET d_id=3 WHERE d_id=2
Error Message:
Msg 547, Level 16, State 0, Line 1
The UPDATE statement conflicted with the REFERENCE constraint "fk_dept_d_fk".
The conflict occurred in database "tempdb", table "dbo.emp", column 'd_fk'.
The statement has been terminated.
UPDATE emp SET d_fk=3 WHERE d_fk=2
Error Message:
Msg 547, Level 16, State 0, Line 1
The UPDATE statement conflicted with the FOREIGN KEY constraint "fk_dept_d_fk".
The conflict occurred in database "tempdb", table "dbo.dept", column 'd_id'.
The statement has been terminated.
We can disable the FK constraints by ALTER statement before the UPDATE and enable them after the UPDATE, like:
-- Disable FK Constraint ALTER TABLE emp NOCHECK CONSTRAINT fk_dept_d_fk -- Perform UPDATE UPDATE dept SET d_id=3 WHERE d_id=2 UPDATE emp SET d_fk=3 WHERE d_fk=2 -- Enable FK Constraint ALTER TABLE emp WITH CHECK CHECK CONSTRAINT fk_dept_d_fk -- Following SELECTS will show the new values in updated records: SELECT * from dept
d_id dept
1 finance
3 hr -- Updated record
SELECT * from emp
sn ename d_fk
1 Manoj 1
2 Saurabh 3 -- Updated record
3 Kanchan 1
4 Pooja 3 -- Updated record
-- Final Cleanup, DROP the tables. DROP TABLE emp DROP TABLE dept
MSDN BOL: http://msdn.microsoft.com/en-us/library/10cetyt6(v=VS.80).aspx