Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make SQL Server use CHECK CONSTRAINT only on inserted or updated rows

I would like to apply a business rule to the rows in a table going forward (SQL Server 2008). However, there is historical data in the table that will not conform to this rule, and there is no good way to make it conform (unknown values with no reasonable defaults.) So I would like the CHECK CONSTRAINT to only be checked on newly inserted rows, or when a row is updated.

I created such a constraint, and set the following values:

  • Check Existing Data On Creation Or Re-Enabling: No
  • Enforce For INSERTs And UPDATEs: Yes
  • Enforce For Replication: Yes

Everything seems fine when I insert a new record. However, if I update a record, the CHECK CONSTRAINT fails even though the updated record conforms to the CHECK CONSTRAINT. It is as if it were trying to apply the constraint to all the rows when a single row is being updated. How can I prevent this?

Here is the constraint:

([DateGiven] IS NULL 
 AND [PrimaryConsultantId] IS NULL 
 AND [AdditionalConsultants] IS NULL 
 AND [ResultingClaLevel] IS NULL)
OR ([DateGiven] IS NOT NULL 
 AND [PrimaryConsultantId] IS NOT NULL 
 AND [AdditionalConsultants] IS NOT NULL 
 AND [ResultingClaLevel] IS NOT NULL))

The updates are being done through a stored proc: (ClaEvaluationId is the primary key)

CREATE PROCEDURE [dbo].[UpdateProc] (
    @ClaEvaluationId int,
    @DateScheduled datetime,
    @DateGiven datetime,
    @PrimaryConsultantId int,
    @AdditionalConsultants nvarchar(500),
    @ResultingClaLevel decimal(2,1)
) AS

SET NOCOUNT ON

UPDATE [dbo].[ClaEvaluation]
SET
    [DateScheduled] = @DateScheduled
    ,[DateGiven] = @DateGiven
    ,[PrimaryConsultantId] = PrimaryConsultantId
    ,[AdditionalConsultants] = @AdditionalConsultants
    ,[ResultingClaLevel] = @ResultingClaLevel
WHERE [ClaEvaluationId] = @ClaEvaluationId
like image 426
Dave Mateer Avatar asked Dec 17 '25 15:12

Dave Mateer


1 Answers

The following line in your procedure is wrong:

,[PrimaryConsultantId] = PrimaryConsultantId

should be

,[PrimaryConsultantId] = @PrimaryConsultantId

Your constraint is working as expected, and exposing a bug for you.

like image 75
A-K Avatar answered Dec 19 '25 07:12

A-K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!