How to Insert Default value of Column In Case of Check Constraint Violation Error

  • Declare @Var int

    Set @Var=5

    Create table Table(id int)

    ALTER TABLE [dbo].[Table1] WITH NOCHECK ADD CONSTRAINT [CK_Table1_ID] CHECK (([ID]>=(0) AND [ID]<=(3)))

    GO

    ALTER TABLE [dbo].[Table1] CHECK CONSTRAINT [CK_Table1_ID]

    Go

    ALTER TABLE [dbo].[Table1] ADD CONSTRAINT [DF_Table1_Id] DEFAULT ((0)) FOR [ID]

    Insert into Table

    select @Var

    Result Expected :@Var Violates the Check Constraint,Default Constraint Value should be inserted

  • Try this:-

    Create table Table1(id int)

    ALTER TABLE [dbo].[Table1] WITH NOCHECK ADD CONSTRAINT [CK_Table1_ID] CHECK (([ID]>=(0) AND [ID]<=(3)))

    GO

    ALTER TABLE [dbo].[Table1] CHECK CONSTRAINT [CK_Table1_ID]

    Go

    ALTER TABLE [dbo].[Table1] ADD CONSTRAINT [DF_Table1_Id] DEFAULT ((0)) FOR [ID]

    Declare @Var int

    Set @Var=5

    Insert into Table1

    select @Var

    Your original code didn't run properly (the table name was wrong on the create and insert statements - do'h).

    I suspect, but can't cite a reference atm the the last "go " in the script removes the referencing of the variable.

    -------------------------------Posting Data Etiquette - Jeff Moden [/url]Smart way to ask a question
    There are naive questions, tedious questions, ill-phrased questions, questions put after inadequate self-criticism. But every question is a cry to understand (the world). There is no such thing as a dumb question. ― Carl Sagan
    I would never join a club that would allow me as a member - Groucho Marx

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply