Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Ignoring a contraint

Author  Topic 

sql777
Constraint Violating Yak Guru

314 Posts

Posted - 2003-01-01 : 23:44:28
How can I turn off a contraint on a table while i'm inserting?

Its causing me problems and I need to get this done! :-)

ValterBorges
Master Smack Fu Yak Hacker

1429 Posts

Posted - 2003-01-01 : 23:49:42
From BOL:


G. Disable and reenable a constraint
This example disables a constraint that limits the salaries accepted in the data. WITH NOCHECK CONSTRAINT is used with ALTER TABLE to disable the constraint and allow an insert that would normally violate the constraint. WITH CHECK CONSTRAINT re-enables the constraint.

CREATE TABLE cnst_example
(id INT NOT NULL,
name VARCHAR(10) NOT NULL,
salary MONEY NOT NULL
CONSTRAINT salary_cap CHECK (salary < 100000)
)

-- Valid inserts
INSERT INTO cnst_example VALUES (1,"Joe Brown",65000)
INSERT INTO cnst_example VALUES (2,"Mary Smith",75000)

-- This insert violates the constraint.
INSERT INTO cnst_example VALUES (3,"Pat Jones",105000)

-- Disable the constraint and try again.
ALTER TABLE cnst_example NOCHECK CONSTRAINT salary_cap
INSERT INTO cnst_example VALUES (3,"Pat Jones",105000)

-- Reenable the constraint and try another insert, will fail.
ALTER TABLE cnst_example CHECK CONSTRAINT salary_cap
INSERT INTO cnst_example VALUES (4,"Eric James",110000)



Go to Top of Page

sql777
Constraint Violating Yak Guru

314 Posts

Posted - 2003-01-01 : 23:58:46
wierd, I disabled it and it still says its violating the contraint (same name).

Its a unique contrainst btw.

-- Reenable the constraint and try another insert, will fail.
ALTER TABLE users CHECK CONSTRAINT IX_Users_UniqueEmail

ANy ideas?



Edited by - sql777 on 01/01/2003 23:59:34
Go to Top of Page

sql777
Constraint Violating Yak Guru

314 Posts

Posted - 2003-01-02 : 00:17:38
I can't seem to drop the constraint using EM because it says the constraint is '..being used for UNIQUE KEY constraint enforcement'.

Ideas please?

TIA

Go to Top of Page

ValterBorges
Master Smack Fu Yak Hacker

1429 Posts

Posted - 2003-01-02 : 02:53:25
I believe you'd have to drop it and then recreate it.
However this does defeat the purpose of having a unique constraint.

ALTER TABLE users DROP CONSTRAINT IX_Users_UniqueEmail

ALTER TABLE users WITH NOCHECK ADD CONSTRAINT IX_Users_UniqueEmail UNIQUE (colname)

Go to Top of Page
   

- Advertisement -