Конфликт инструкции alter table с ограничением foreign key sql

Why does add a foreign key to the tblDomare table result in this error?

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint «FK__tblDomare__PersN__5F7E2DAC». The conflict occurred in database «almu0004», table «dbo.tblBana», column ‘BanNR’.

Code

CREATE TABLE tblDomare
(PersNR VARCHAR (15) NOT NULL,
fNamn VARCHAR (15) NOT NULL,
eNamn VARCHAR (20) NOT NULL,
Erfarenhet VARCHAR (5),
PRIMARY KEY (PersNR));

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (7606091347,'Josefin','Backman',4);

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (8508284163,'Johanna','Backman',1);

CREATE TABLE tblBana
(BanNR VARCHAR (15) NOT NULL,
PRIMARY KEY (BanNR));

INSERT INTO tblBana (BanNR)
Values (1);

INSERT INTO tblBana (BanNR)
Values (2);

INSERT INTO tblBana (BanNR)
Values (3);

ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);

ΩmegaMan's user avatar

ΩmegaMan

29.6k12 gold badges100 silver badges122 bronze badges

asked Feb 17, 2014 at 21:09

user3162932's user avatar

0

It occurred because you tried to create a foreign key from tblDomare.PersNR to tblBana.BanNR but/and the values in tblDomare.PersNR didn’t match with any of the values in tblBana.BanNR. You cannot create a relation which violates referential integrity.

answered Feb 17, 2014 at 21:16

Smutje's user avatar

SmutjeSmutje

17.8k4 gold badges24 silver badges41 bronze badges

8

This query was very useful for me. It shows all values that don’t have any matches

select FK_column from FK_table
WHERE FK_column NOT IN
(SELECT PK_column from PK_table)

answered Jul 4, 2016 at 8:22

dantey89's user avatar

dantey89dantey89

2,17724 silver badges37 bronze badges

1

Try this solution:

There is a data item in your table whose associated value doesn’t exist in the table you want to use it as a primary key table.
Make your table empty or add the associated value to the second table.

DreamTeK's user avatar

DreamTeK

32.6k27 gold badges112 silver badges172 bronze badges

answered Apr 6, 2018 at 7:34

PatsonLeaner's user avatar

PatsonLeanerPatsonLeaner

1,23215 silver badges26 bronze badges

1

It is possible to create the foreign key using ALTER TABLE tablename WITH NOCHECK …, which will allow data that violates the foreign key.

«ALTER TABLE tablename WITH NOCHECK …» option to add the FK — This solution worked for me.

answered Aug 9, 2016 at 6:19

Ankita Biswas's user avatar

4

Remove all existing data from your tables and then make a relation between the tables.

ΩmegaMan's user avatar

ΩmegaMan

29.6k12 gold badges100 silver badges122 bronze badges

answered Aug 20, 2015 at 7:21

max's user avatar

maxmax

2292 silver badges3 bronze badges

3

Before You add Foreign key to the table, do the following

  1. Make sure the table must empty or The column data should match.
  2. Make sure it is not null.
  3. If the table contains do not go to design and change, do it manually.

    alter table Table 1 add foreign key (Column Name) references Table 2 (Column Name)

    alter table Table 1 alter column Column Name attribute not null

soccer7's user avatar

soccer7

3,5773 gold badges29 silver badges50 bronze badges

answered Sep 1, 2015 at 5:08

GirishBabuC's user avatar

GirishBabuCGirishBabuC

1,26715 silver badges20 bronze badges

I guess, a column value in a foreign key table should match with the column value of the primary key table. If we are trying to create a foreign key constraint between two tables where the value inside one column(going to be the foreign key) is different from the column value of the primary key table then it will throw the message.

So it is always recommended to insert only those values in the Foreign key column which are present in the Primary key table column.

For ex. If the Primary table column has values 1, 2, 3 and in Foreign key column the values inserted are different, then the query would not be executed as it expects the values to be between 1 & 3.

answered Nov 27, 2014 at 15:46

sam05's user avatar

sam05sam05

1992 silver badges4 bronze badges

In very simple words your table already has data present in it and the table you are trying to create relationship with does have that Primary key set for the values that are already present.

  1. Either delete all the values of the existing table.
  2. Add all the values of foreign key reference in the new table.

answered Oct 27, 2021 at 10:27

Ralph B. Roman's user avatar

Try DELETE the current datas from tblDomare.PersNR . Because the values in tblDomare.PersNR didn’t match with any of the values in tblBana.BanNR.

propoLis's user avatar

propoLis

1,2291 gold badge14 silver badges48 bronze badges

answered Jun 8, 2018 at 6:50

Thinker Bell's user avatar

1

When you define a Foreign Key in table B referencing the Primary Key of table A it means that when a value is in B, it must be in A. This is to prevent unconsistent modifications to the tables.

In your example, your tables contain:

tblDomare with PRIMARY KEY (PersNR):

PersNR     |fNamn     |eNamn      |Erfarenhet
-----------|----------|-----------|----------
6811034679 |'Bengt'   |'Carlberg' |10
7606091347 |'Josefin' |'Backman'  |4
8508284163 |'Johanna' |'Backman'  |1
---------------------------------------------

tblBana:

BanNR
-----
1
2
3
-----

This statement:

ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);

says that any line in tblDomare with key PersNR must have a correspondence in table tblBana on key BanNR. Your error is because you have lines inserted in tblDomare with no correspondence in tblBana.

2 solutions to fix your issue:

  • either add lines in tblBana with BanNR in (6811034679, 7606091347, 8508284163)
  • or remove all lines in tblDomare that have no correspondence in tblBana (but your table would be empty)

General advice: you should have the Foreign Key constraint before populating the tables. Foreign keys are here to prevent the user of the table from filling the tables with inconsistencies.

answered Jun 3, 2020 at 12:40

belka's user avatar

belkabelka

1,4901 gold badge18 silver badges31 bronze badges

1

i had this error too
as Smutje reffered make sure that you have not a value in foreign key column of your base foreign key table that is not in your reference table i.e(every value in your base foreign key table(value of a column that is foreign key) must also be in your reference table column)
its good to empty your base foreign key table first then set foreign keys

answered Feb 2, 2015 at 6:06

ako's user avatar

the data you have entered a table(tbldomare) aren’t match a data you have assigned primary key table. write between tbldomare and add this word (with nocheck) then execute your code.

for example you entered a table tbldomar this data

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);

and you assigned a foreign key table to accept only 1,2,3.

you have two solutions one is delete the data you have entered a table then execute the code. another is write this word (with nocheck) put it between your table name and add
like this

ALTER TABLE  tblDomare with nocheck
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);

Ataur Rahman Munna's user avatar

answered Nov 2, 2016 at 9:40

khadar's user avatar

Smutje is correct and Chad HedgeCock offered a great layman’s example.
Id like to build on Chad’s example by offering a way to find/delete those records.
We will use Customer as the Parent and Order as the child. CustomerId is the common field.

select * from Order Child 
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null 

if you are reading this thread… you will get results. These are orphaned children. select * from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null Note the row count in the bottom right.

Go verify w/ whomever you need to that you are going to delete these rows!

begin tran 
delete Order
from Order Child 
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null 

Run the first bit.
Check that row count = what you expected

commit the tran

commit tran 

Be careful. Someone’s sloppy programming got you into this mess. Make sure you understand the why before you delete the orphans. Maybe the parent needs to be restored.

answered Nov 16, 2017 at 18:11

greg's user avatar

greggreg

1,6831 gold badge17 silver badges30 bronze badges

1

From our end, this is the scenario:

  1. We have an existing table in the database with records.
  2. Then I introduces a NOT nullable foreign key
  3. After executing the update i got this error.

How did i solve you ask?

SOLUTION: I just removed all the records of the table, then tried to update the database and it was successful.

answered Jun 1, 2021 at 12:46

VJPPaz's user avatar

VJPPazVJPPaz

9177 silver badges21 bronze badges

This happens to me, since I am designing my database, I notice that I change my seed on my main table, now the relational table has no foreign key on the main table.

So I need to truncate both tables, and it now works!

answered Mar 16, 2018 at 17:46

Willy David Jr's user avatar

Willy David JrWilly David Jr

8,6226 gold badges46 silver badges57 bronze badges

You should see if your tables has any data on the rows. If «yes» then you should truncate the table(s) or else you can make them to have the same number of data at tblDomare.PersNR to tblBana.BanNR and vise-verse.

answered Oct 23, 2018 at 21:44

adrianex03's user avatar

In my scenario, using EF, upon trying to create this new Foreign Key on existing data, I was wrongly trying to populate the data (make the links) AFTER creating the foreign key.

The fix is to populate your data before creating the foreign key since it checks all of them to see if the links are indeed valid. So it couldn’t possibly work if you haven’t populated it yet.

answered Aug 9, 2019 at 11:08

jeromej's user avatar

jeromejjeromej

10.6k2 gold badges43 silver badges62 bronze badges

I encounter some issue in my project.

enter image description here

In child table, there isn’t any record Id equals 1 and 11

mage

I inserted DEAL_ITEM_THIRD_PARTY_PO table which Id equals 1 and 11 then I can create FK

answered Oct 21, 2019 at 6:27

Metin Atalay's user avatar

Metin AtalayMetin Atalay

1,39518 silver badges28 bronze badges

Please first delete data from that table and then run the migration again. You will get success

answered Apr 19, 2020 at 16:43

M Arslan Riaz's user avatar

I had the same problem.
My issue was having nullable: true in column (migration file):

AddColumn("dbo.table", "column", c => c.Int(nullable: true));
        

Possible Solutions:

  1. Change nullable ‘false’ to ‘true’. (Not Recommended)
  2. Change property type from int to int? (Recommended)

And if required, change this later after adding column > then missing field data in previous records

If you’ve changed an existing property from nullable to non-nullable:
3) Fill the column data in database records

answered Apr 29, 2021 at 12:15

Ahmed Hafiz's user avatar

A foreign key constraint in a child table must have a parent table with a primary key. The primary key must be unique. The foreign key value must match a value in the patent table primary key

answered May 1, 2021 at 15:52

Golden Lion's user avatar

Golden LionGolden Lion

3,8582 gold badges26 silver badges35 bronze badges

When you alter table column from nullable to not nullable column where this column is foreign key, you must :

  1. Firstly, initialize this column with value (because it is foreign
    key not nullable).

  2. After that you can alter your table column normally.

answered Sep 17, 2021 at 6:23

Amara Miloudi's user avatar

Please try below query:

CREATE TABLE tblBana
(BanNR VARCHAR (15) NOT NULL PRIMARY KEY,

);

CREATE TABLE tblDomare
(PersNR VARCHAR (15) NOT NULL PRIMARY KEY,
fNamn VARCHAR (15) NOT NULL,
eNamn VARCHAR (20) NOT NULL,
Erfarenhet VARCHAR (5),
FK_tblBana_Id VARCHAR (15) references  tblBana (BanNR)
);


INSERT INTO tblBana (BanNR)
Values (3);


INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet,FK_tblBana_Id)
Values (8508284173,'Johanna','Backman',1,3);

answered Dec 9, 2021 at 7:01

RainyTears's user avatar

or you can use this

SELECT  fk_id FROM dbo.tableA
Except
SELECT fk_id From dbo.tableB

desertnaut's user avatar

desertnaut

57.7k27 gold badges140 silver badges167 bronze badges

answered Apr 16, 2021 at 9:13

Christian Møller's user avatar

and just FYI, in case you do all of your data reference checks and find no bad data…apparently it is not possible to create a foreign key constraint between two tables and fields where those fields are the primary key in both tables! Do not ask me how I know this.

answered Jul 10, 2017 at 15:13

Doug Boude's user avatar

Doug BoudeDoug Boude

271 silver badge5 bronze badges

0 / 0 / 3

Регистрация: 08.10.2012

Сообщений: 141

1

25.09.2014, 22:34. Показов 51449. Ответов 5


Студворк — интернет-сервис помощи студентам

пытаюсь сделать связь таблиц
В таблице Сотрудник столбец КодСотрудника является первичным ключом, а в таблице Квартиры столбец КодСотрудника является вторичным ключом, но мне выдает такую вот ошибку. Значение везде int
Конфликт инструкции ALTER TABLE с ограничением FOREIGN KEY «FK_Операция_Сотрудник». Конфликт произошел в базе данных «ned», таблица «dbo.Сотрудник», column ‘КодСотрудника’.
Да, при создании другой связи «id» из Квартиры и КодКвартиры выдаёт такую же ошибку.

Миниатюры

Конфликт инструкции ALTER TABLE
 

Конфликт инструкции ALTER TABLE
 



0



Я Фоюмчанин ? дааааа)

213 / 204 / 23

Регистрация: 02.06.2012

Сообщений: 1,424

Записей в блоге: 12

25.09.2014, 22:44

2

Цитата
Сообщение от вредина
Посмотреть сообщение

, а в таблице Квартиры столбец КодСотрудника

А там и нет такого столбца…
И если вы пытаетесь связать сотрудников и квартиры то делаете огромную ошибку
У вас будут 3 таблицы по кругу ссылающиеся на друг друга



0



0 / 0 / 3

Регистрация: 08.10.2012

Сообщений: 141

25.09.2014, 23:22

 [ТС]

3

тьфу, не из «Квартиры», а из Операции запутался. На 2-ом скрине связи видны. КодСотрудника с Кодом сотрудника (табл. Операция-Сотрудник) и id и КодКвартиры (табл Квартиры и Операции)

Добавлено через 9 минут
данные есть во всех трех таблицах



0



63 / 63 / 21

Регистрация: 08.02.2013

Сообщений: 262

26.09.2014, 09:33

4

Лучший ответ Сообщение было отмечено вредина как решение

Решение

вероятно, есть данные в таблице Операция со значением в поле КодСотрудника, которого нет в таблице Сотрудник в соответствующем поле.
Попробуйте удалить данные из таблиц и связать пустые таблицы. Если получится, то мое предположение верно.



6



0 / 0 / 3

Регистрация: 08.10.2012

Сообщений: 141

26.09.2014, 10:22

 [ТС]

5

nixon93nixon, вечером проверю, спасибо



0



0 / 0 / 3

Регистрация: 08.10.2012

Сообщений: 141

27.09.2014, 22:37

 [ТС]

6

nixon93nixon, да, в этом была ошибка, спасибо.



0



Здраствуйте, возникла такая проблема, я хочу поставить связь от fact к dimension2 по ключу KOATUU и от dimension3 к dimension2 по ключу nameLocality, но возникают ошибки такого характера:
[SQL Server]Конфликт инструкции ALTER TABLE с ограничением FOREIGN KEY "FK__fact__KOATUU__505BE5AD". Конфликт произошел в базе данных "OLAP", таблица "dbo.dimension2", column \'KOATUU\'.
введите сюда описание изображения
введите сюда описание изображения
Хочу, чтобы вот так было. Подскажите, пожалуйста, что делаю не так и как стоит сделать. Буду очень благодарен.
Ниже представлено, как создавал ключи и связи, а также таблицы

ALTER TABLE fact ALTER COLUMN id int not null
ALTER TABLE fact ALTER COLUMN KOATUU bigint not null
ALTER TABLE fact ALTER COLUMN OPER_CODE int not null
ALTER TABLE fact ALTER COLUMN DEP_CODE int not null
ALTER TABLE departament ALTER COLUMN DEP_CODE int not null
ALTER TABLE operation ALTER COLUMN OPER_CODE int not null")
ALTER TABLE fact ADD PRIMARY KEY (id,KOATUU,OPER_CODE,DEP_CODE)
ALTER TABLE departament ADD PRIMARY KEY (DEP_CODE)
ALTER TABLE operation ADD PRIMARY KEY (OPER_CODE)
ALTER TABLE fact ADD FOREIGN KEY (DEP_CODE) REFERENCES departament(DEP_CODE)
ALTER TABLE fact ADD FOREIGN KEY (OPER_CODE) REFERENCES operation(OPER_CODE)
ALTER TABLE dimension2 ALTER COLUMN KOATUU bigint not null
ALTER TABLE dimension2 ALTER COLUMN nameLocality varchar(255) not null
ALTER TABLE dimension3 ALTER COLUMN nameLocality varchar(255) not null
ALTER TABLE dimension2 ADD PRIMARY KEY (KOATUU,nameLocality)
ALTER TABLE dimension3 ALTER COLUMN id int not null
ALTER TABLE dimension3 ADD PRIMARY KEY (id,nameLocality)
ALTER TABLE fact ADD FOREIGN KEY (KOATUU) REFERENCES dimension2(KOATUU)
ALTER TABLE dimension3 ADD FOREIGN KEY (nameLocality) REFERENCES dimension2(nameLocality)

Fact:

CREATE TABLE [dbo].[fact](
    [id] [int] NOT NULL,
    [KOATUU] [bigint] NOT NULL,
    [OPER_CODE] [int] NOT NULL,
    [D_REG] [varchar](max) NULL,
    [DEP_CODE] [int] NOT NULL,
    [BRAND] [varchar](max) NULL,
    [MODEL] [varchar](max) NULL,
    [MAKE_YEAR] [bigint] NULL,
    [COLOR] [varchar](max) NULL,
    [KIND] [varchar](max) NULL,
    [BODY] [varchar](max) NULL,
    [PURPOSE] [varchar](max) NULL,
    [FUEL] [varchar](max) NULL,
    [CAPACITY] [float] NULL,
    [OWN_WEIGHT] [varchar](max) NULL,
    [TOTAL_WEIGHT] [varchar](max) NULL,
    [N_REG_NEW] [varchar](max) NULL,
PRIMARY KEY CLUSTERED 
(
    [id] ASC,
    [KOATUU] ASC,
    [OPER_CODE] ASC,
    [DEP_CODE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[fact]  WITH CHECK ADD FOREIGN KEY([DEP_CODE])
REFERENCES [dbo].[departament] ([DEP_CODE])
GO

ALTER TABLE [dbo].[fact]  WITH CHECK ADD FOREIGN KEY([OPER_CODE])
REFERENCES [dbo].[operation] ([OPER_CODE])

Departament:

CREATE TABLE [dbo].[departament](
    [DEP_CODE] [int] NOT NULL,
    [DEP] [varchar](max) NULL,
PRIMARY KEY CLUSTERED 
(
    [DEP_CODE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Operation:

CREATE TABLE [dbo].[operation](
    [OPER_CODE] [int] NOT NULL,
    [OPER_NAME] [varchar](max) NULL,
PRIMARY KEY CLUSTERED 
(
    [OPER_CODE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Dimension2:

CREATE TABLE [dbo].[dimension2](
    [administrativeTeritorialUnit] [varchar](max) NULL,
    [nameAdministrativeTeritorialUnit] [varchar](max) NULL,
    [KOATUU] [bigint] NOT NULL,
    [nameMedicalInstitution] [varchar](max) NULL,
    [nameObject] [varchar](max) NULL,
    [typeInstitution] [varchar](max) NULL,
    [locality] [varchar](max) NULL,
    [nameLocality] [varchar](255) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [KOATUU] ASC,
    [nameLocality] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Dimension3:

CREATE TABLE [dbo].[dimension3](
    [id] [int] NOT NULL,
    [OBL_NAME] [varchar](max) NULL,
    [STREET_NAME] [varchar](max) NULL,
    [type] [varchar](max) NULL,
    [nameLocality] [varchar](255) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [id] ASC,
    [nameLocality] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

I am trying to add a new foreign key to an existing table where there is data in the column I am wanting to make a change to.

In dev, I have tried this where data does and does not exist. Where there is no data this works fine.

ALTER TABLE [rpt].ReportLessonCompetency WITH CHECK
ADD CONSTRAINT [FK_Grade_TraineeGrade_Id]
FOREIGN KEY (Grade) REFERENCES [rpt].TraineeGrade(Id)

Where there is data I get the following error

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint «FK_Grade_TraineeGrade_Id». The conflict occurred in database «T_test», table «Core.Report.TraineeGrade», column ‘Id’.

I would be grareful if someone could let me know what I need to do in order to ensure that this works where data does and does not exist as I cannot control if the live database will or will not have any existing data.

Thanks

Simon

asked Jul 12, 2019 at 6:22

Simon Price's user avatar

Simon PriceSimon Price

1831 gold badge2 silver badges8 bronze badges

1

You probably receive the error because you have orphaned records in the [rpt].[ReportLessonCompetency] table.
An orphaned record is a record in a child table without a corresponding parent record in the parent table. In your case the [rpt].[ReportLessonCompetency] will contain values
for [Grade] that don’t exist in the [rpt].TraineeGrade(Id) table.

There are 2 options to get the foreign key created (though there’s only 1 valid option imo).

Cleanup your data
First you could look up the records in the child table that don’t have a corresponding parent record. Next, you should either delete/update those records in the child table or add the missing parent records to your parent table. Afterwards you’ll be able to create the foreign key constraint. This is the best option by far since your referential integrety is guaranteed and your foreign key will be trusted.
You can find orphaned records by executing following query:

SELECT *
FROM [rpt].ReportLessonCompetency rlc
WHERE NOT EXISTS
(
    SELECT 1 
    FROM [rpt].TraineeGrade tg
    WHERE tg.Id = rlc.Grade
)

WITH NOCHECK
The other option would be to create the foreign key with WITH NOCKECK. SQL Server will create the foreign key without verifying the existing data in the table. When you update/insert data in the child table, those records will still be checked.
Consequently, your foreign key will be marked as untrusted and the query optimizer won’t consider your constraint to generate an execution plan.
Here you can find an example of how performance can be impacted.

answered Jul 12, 2019 at 8:49

Thomas Costers's user avatar

1

You can avoid verifying FOREIGN KEY constraints against existing data by using WITH NOCHECK.

ALTER TABLE [rpt].ReportLessonCompetency WITH NOCHECK
ADD CONSTRAINT [FK_Grade_TraineeGrade_Id]
FOREIGN KEY (Grade) REFERENCES [rpt].TraineeGrade(Id)

I wouldn’t recommend doing this as ignored constraint violations can cause an update to fail at a later point. You should clean up your data instead.

answered Jul 12, 2019 at 8:44

Tahir Riaz's user avatar

If you are a developer dealing with database management, you must have come across the ‘Alter Table Statement Conflicted with Foreign Key Constraint’ error. This error occurs when you try to alter a table which has a foreign key constraint that references other tables. It can be frustrating, especially when you are not familiar with the solution. In this guide, we will discuss how to resolve this error step-by-step.

Step 1: Identify the Foreign Key Constraint

The first step in resolving this error is to identify the foreign key constraint causing the conflict. You can use the following SQL query to list all the foreign key constraints in your database:

SELECT f.name AS foreign_key_name,
   OBJECT_NAME(f.parent_object_id) AS table_name,
   COL_NAME(fc.parent_object_id,
   fc.parent_column_id) AS constraint_column_name,
   OBJECT_NAME (f.referenced_object_id) AS referenced_object,
   COL_NAME(fc.referenced_object_id,
   fc.referenced_column_id) AS referenced_column_name
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id

This query will list all the foreign key constraints in your database with their table names, column names, and referenced tables and columns. From the result, you can identify the foreign key constraint causing the conflict.

Step 2: Disable the Foreign Key Constraint

Once you have identified the foreign key constraint causing the conflict, the next step is to disable it temporarily. You can use the following SQL query to disable the foreign key constraint:

ALTER TABLE <Table_Name> NOCHECK CONSTRAINT <Constraint_Name>

Replace <Table_Name> with the name of the table containing the foreign key constraint, and <Constraint_Name> with the name of the foreign key constraint causing the conflict.

Step 3: Execute the ALTER TABLE Statement

After disabling the foreign key constraint, you can now execute the ALTER TABLE statement that was causing the conflict. Once the statement is executed successfully, you can re-enable the foreign key constraint using the following SQL query:

ALTER TABLE <Table_Name> WITH CHECK CHECK CONSTRAINT <Constraint_Name>

Replace <Table_Name> and <Constraint_Name> with the table name and constraint name you disabled in step 2.

FAQ

Q1. Can I disable all foreign key constraints in my database?

A1. No, you cannot disable all foreign key constraints in your database. Disabling a foreign key constraint can cause data inconsistencies and violate referential integrity.

Q2. Can I use the same name for a foreign key constraint in different tables?

A2. Yes, you can use the same name for a foreign key constraint in different tables.

Q3. Can I disable a foreign key constraint permanently?

A3. No, you should not disable a foreign key constraint permanently. It can cause data inconsistencies and violate referential integrity.

Q4. Can I re-enable a foreign key constraint without checking it?

A4. Yes, you can re-enable a foreign key constraint without checking it using the following SQL query:

ALTER TABLE <Table_Name> WITH NOCHECK CHECK CONSTRAINT <Constraint_Name>

Replace <Table_Name> and <Constraint_Name> with the table name and constraint name you disabled in step 2.

Q5. What is referential integrity?

A5. Referential integrity is a database constraint that ensures that data relationships between tables are valid and consistent. It prevents orphaned records and maintains data consistency.

Conclusion

In this guide, we discussed how to resolve the ‘Alter Table Statement Conflicted with Foreign Key Constraint’ error in SQL Server. We provided a step-by-step solution that involves identifying the foreign key constraint causing the conflict, disabling it temporarily, executing the ALTER TABLE statement, and re-enabling the foreign key constraint. We also discussed some frequently asked questions related to foreign key constraints and referential integrity. Hopefully, this guide has helped you resolve the error and improve your database management skills.

  • How to Create Foreign Key Constraints in SQL Server
  • Understanding Referential Integrity and Foreign Keys in SQL Server
  • Disabling Constraints in SQL Server

Понравилась статья? Поделить с друзьями:
  • Поздравление с 23 февраля руководству в стихах
  • Должностная инструкция врача эндоскописта по профстандарту
  • Бетавер инструкция по применению цена отзывы аналоги кому прописывают
  • Автолис руководство по эксплуатации
  • Руководство по защите людей