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

alter FUNCTION [Kuri].[fnGetAge](@kuri_cust_Id int,@amt decimal)
RETURNS SMALLINT
AS
    BEGIN
    DECLARE @isVallid  bit = 0
    declare @payed decimal(14,2)
    declare @totaltillnow decimal(14,2)
    select @payed = isnull(SUM(Payment.amt),0)  from Kuri.Payment where Payment.Kuri_Cust_ID = @kuri_Cust_id
    select @totaltillnow = isnull(SUM(NextLotAmount),0) from Kuri.Kuri_GivenDetails
    inner join Kuri.kuri_Customer  
    on Kuri_GivenDetails.kuri_Id  = kuri_Customer.kuri_ID 
     where kuri_Customer.kuri_Cust_id =  @kuri_Cust_id
     if((@payed + @amt) < @totaltillnow)
        set @isVallid = 1
        RETURN @isVallid
    END;
GO

ALTER TABLE [Kuri].[Payment]  WITH CHECK ADD  CONSTRAINT PaymentCheck CHECK (kuri.fnGetAge(kuri_Cust_ID,amt) >= 1 )
GO

error :

The ALTER TABLE statement conflicted with the CHECK constraint
«PaymentCheck». The conflict occurred in database «MERP», table
«Kuri.Payment».

Table structure is like this

CREATE TABLE [Kuri].[Payment](
    [payment_ID] [int] IDENTITY(1,1) NOT NULL,
    [payment_Date] [date] NOT NULL,
    [bill_No] [nvarchar](25) NOT NULL,
    [Kuri_Cust_ID] [int] NOT NULL,
    [vr_ID] [int] NOT NULL,
    [amt] [decimal](14, 2) NULL,
    [created_ID] [int] NULL,
    [created_Date] [datetime] NULL,
    [modified_ID] [int] NULL,
    [modified_Date] [datetime] NULL,
    [authorized_ID] [int] NULL,
    [authorized_Date] [datetime] NULL,
  CONSTRAINT [PK_Payment] PRIMARY KEY CLUSTERED 
  ([payment_ID] ASC)

 ALTER TABLE [Kuri].[Payment]  WITH CHECK ADD  CONSTRAINT [FK_Payment_kuri_Customer] FOREIGN KEY([Kuri_Cust_ID])
 REFERENCES [Kuri].[kuri_Customer] ([Kuri_Cust_ID])

 ALTER TABLE [Kuri].[Payment] CHECK CONSTRAINT [FK_Payment_kuri_Customer]

I need to check datecom is less than datelivr

create table Commande
(
Numcom int identity primary key,
Datecom date,
Datelivr date,
Codecli int foreign key references clients (Codecli) 
)

alter table Commande 
    add constraint date_check check(datediff(day,Datecom,Datelivr) > 0)

but I get the error message:

The ALTER TABLE statement conflicted with the CHECK constraint
«date_check». The conflict occurred in database «tp4», table
«dbo.Commande».

How can this happen?

asked Sep 21, 2015 at 11:03

The error message is self-explanatory: Your check constraint is trying to enforce that all values in Datecom are at least one day earlier than Datelivr, but you must have at least one row where this is not true — either Datecom is the same day, later, or one of the values is NULL. Find those rows using:

SELECT Numcom, Datecom, Datelivr
FROM dbo.Commade
WHERE datediff(day,Datecom,Datelivr) <= 0
  OR Datecom IS NULL
  OR Datelivr IS NULL;

answered Sep 21, 2015 at 11:20

Aaron BertrandAaron Bertrand

182k28 gold badges404 silver badges622 bronze badges

2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Scenario:

You are working as SQL Server developer, you are asked to add Check Constraint to one existing table dbo.Employee on FName column and write logic for Check Constraint so it should always accept alphabets.

When you tried to add Check Constraint, you got below error.

Msg 547, Level 16, State 0, Line 19
The ALTER TABLE statement conflicted with the CHECK constraint «Chk_dbo_Employee_FName». 
The conflict occurred in database «YourDatabaseName», table «dbo.Employee», column ‘FName’.

Solution:

Let’s generate the scenario first for the error. Create sample dbo.Employee table with some sample data.

--Create Table  
use YourDatabaseName
go
Create table dbo.Employee
(
FName VARCHAR(100) Not Null,
LName VARCHAR(100),
StreetAddress VARCHAR(255)
)
--Insert data in sql table
insert into dbo.Employee(FName,LName,StreetAddress)
values ('Aamir','Shahzad','xyz address')
go
insert into dbo.Employee(FName,LName,StreetAddress)
values ('Raza A',Null,'abc address')
go

Now run the alter table statement to add Check Constraint.  Once you will execute this statement you will get above error. as existing data does not qualify for Check Constraint. We have space in first name for ‘Raza A’ and our Check Constraint says that the data in FName should be always alphabets.

Alter table dbo.Employee
Add Constraint Chk_dbo_Employee_FName
Check (FName not like '%[^a-z]%')



1) First Solution: Correct Existing Data

Fist solution can be, you find the data that does not qualify for Check Constraint and correct that and then add Check Constraint.

2) If business don’t want to fix the existing data and want to implement Check Constraint from moving forward, you can create the Check Constraint with Nocheck. By doing that it will not validate existing data against our Check Constraint rule but only apply to new data.

Alter table dbo.Employee with nocheck
Add Constraint Chk_dbo_Employee_FName
Check (FName not like '%[^a-z]%') 



Let’s insert couple of records and check if our Constraint is working as expected.

insert into dbo.Employee(FName,LName,StreetAddress)
values ('Test 123',Null,'test address')
go

insert into dbo.Employee(FName,LName,StreetAddress)
values ('Najaf',Null,'test address')
go



The first insert will fail as it does not qualify with our Check Constraint rule. Second record will be inserted successfully. Let’s check the data in table now.

How to add Check Constraint to Column with Existing Data in SQL Server 

Video Demo : How to fix error the Alter table statement conflicted with the Check Constraint

Today, I worked on a service request where our customer faced the following error: The ALTER TABLE statement conflicted with the CHECK constraint «Table1». The conflict occurred in database «DatabaseName», table «Table2».

Full error message:

Microsoft.Data.Tools.Diagnostics.Tracer Verbose: 0 : 2023-01-11T11:11:35 : Executing Step 341, Not Tracked, Type ‘EnableConstraintsStep’, Section ‘None’, Operation ‘0’, Ignorable Errors ‘None’, Script is as follows: PRINT N’Checking constraint: table1_table2_updatedby_foreign [dbo].[Table1]’; ALTER TABLE [dbo].[Table1] WITH CHECK CHECK CONSTRAINT [table1_table2_updatedby_foreign];

Microsoft.Data.Tools.Diagnostics.Tracer Error: 19 : 2023-01-11T11:11:39 : Retry requested: Retry count = 1. Delay = 00:00:00.2500000, SQL Error Code = -2146232060, SQL Error Number = 547, Can retry error = True, Will retry = True Microsoft.Data.SqlClient.SqlException (0x80131904): The ALTER TABLE statement conflicted with the CHECK constraint «Table1». The conflict occurred in database «DatabaseName», table «Table2». Error Number:547,State:0,Class:16

This situation happened at the moment that the process has inserted all the rows in all tables and needs to enable the constrains/indexes. Points that a foreign key doesn’t exist in the related table. You could see more details here «For an export to be transactionally consistent, you must ensure either that no write activity is occurring during the export, or that you are exporting from a transactionally consistent copy of your database.» based on this link 

The solution is to export the data again, avoiding any writing operation in the database during this process. After it, initiate again the import process.

Enjoy!

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

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Насосная станция джилекс джамбо 60 35 н 24 инструкция по эксплуатации
  • Инструкция на бортовой компьютер multitronics comfort x14
  • Каркасный дом своими руками пошаговая инструкция 8х8 одноэтажный
  • Массажное кресло bodo ecto sport инструкция
  • Измельчитель moulinex fresh express dj755g32 инструкция