The check keyword not working in sql management studio - sql

I have two tables tblA and tblB. And a constraint called tblA_tblB_FK is created between these tables. I wanted to update both columns in tables chained with tblA_tblB_FK constraint. While reading different posts I thought the best way is to disable the constraint for a moment and enable again after the update. For that reason I executed these queries:
alter table tblA NOCHECK CONSTRAINT tblA_tblB_FK
After this step I did the update and till now everything was OK, but then I tried to enable again the constraint, so I executed this query:
ALTER TABLE tblA CHECK CONSTRAINT tblA_tblB_FK
and it says command successfully completed. But when I try to make update again it doesn't stop me from doing that, meaning there is a problem with the enabling process. I tried to execute another query:
ALTER TABLE tblA WITH CHECK CHECK CONSTRAINT tblA_tblB_FK
and it doesn't allow me complaining there is tblA_tblB_Fk constraint active. I don't understand why it allows me to make an update, while it doesn't allow me to execute this command?
I am using SQL Server 2005. Thanks in advance for any suggestions!

Check you insert and update specification for the foreign key in management studio under Table>Table_name>Keys folder. It might be set to "Cascade".

Related

Inserting new record and skip if foreign key conflict in sql server 2008 R2

I have the problem similar to this one SQL Server foreign key conflict in a multi values statement? However, in sql server 2008.
While I am reading data from csv file, there is some id already not exist in parent and thus return this error:
INSERT statement conflicted with the FOREIGN KEY constraint
May I know if there is a way similar to MySQL insert ignore. Such that I can simply skip the problematic data.
I accept that if there is no method other than creating a stored procedure with a new temp table (insert into a table without foreign key first, and then re-insert with where foreign_id exists in (select id from parent)).
As I really cannot find any in documentation, asking for ensuring I didn't miss anything.
One general solution which comes to mind would be to temporarily turn off the foreign key constraints, and do the insert. Then, afterwards, you may run a cleanup script/query to remove or rectify child records which are pointing to parents which do not exist. Once your data is in good shape, then turn on the foreign key constraints again.
Read How can foreign key constraints be temporarily disabled using T-SQL? to learn how to disable/enable a foreign key constraint for a single table:
ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint -- disable
ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint -- enable

ADD and DROP SQL Server table constraint command in one transaction caused error

I have more SQL scripts (each for different version of the application) and I want to execute all scripts in one transaction.
I'm executing it from c# using:
ExecuteNonQuery(command, conn, trans)
on SqlCommand.
The SQL commands in the scripts are separated by GO separators. My C# code iterates through all scripts and creates collection of the SqlCommand based on the GO separator. The GO separator is excluded from SqlCommand execution. It is just a separator in script file.
All was working fine, but I have found one problem. I have in one script the following command:
ALTER TABLE [dbo].[RoleDataPermissions] WITH NOCHECK ADD CONSTRAINT
[FK_RoleDataPermissions_OrganizationUnits] FOREIGN KEY([OrganizationUnitID])
REFERENCES [OrganizationUnits] ([ID])
and in the another script (in another version of app this constraint was deleted) I have:
ALTER TABLE [dbo].[RoleDataPermissions]
DROP CONSTRAINT FK_RoleDataPermissions_OrganizationUnits
The first command passed fine, but the second one throws the exception:
'FK_RoleDataPermissions_OrganizationUnits' is not a constraint. Could not drop constraint. See previous errors.
I'm trying find out what is causing this problem. I think, that the problem is, that if all commands are executed under one transaction, so the first command is not committed and then the second one cannot find this constraint. I have tried also change the isolation level to readuncommited, but it doesn't help.
Do you have any idea how to deal with this?
thanks
Your analysis is not correct as a transaction can see it's own uncommitted data. This is easily demonstrated as below.
CREATE TABLE T1
(
ID INT PRIMARY KEY
)
CREATE TABLE T2
(
ID INT
)
BEGIN TRAN
ALTER TABLE T2
WITH NOCHECK ADD CONSTRAINT FK_Test FOREIGN KEY(ID) REFERENCES T1
GO
ALTER TABLE T2
DROP CONSTRAINT FK_Test
COMMIT
DROP TABLE T1, T2
The syntax you have posted is invalid however so quite likely the constraint isn't being created due to the syntax error and for some reason the exception isn't being reported in your application. Or (if your actual syntax is correct) maybe you are dropping the constraint twice.

check constraint in generated scripts

In SSMS, Tasks > Generate Scripts, I have selected a few tables and in the generated SQL I get:
ALTER TABLE [Project] WITH CHECK ADD CONSTRAINT [FK_Project_aspnet_Users] FOREIGN KEY([UserId])
REFERENCES [aspnet_Users] ([UserId])
GO
ALTER TABLE [Project] CHECK CONSTRAINT [FK_Project_aspnet_Users]
GO
Why does it CHECK in the second statement if WITH CHECK is specified in the first? The second statement appears directly after the first.
TIA
You are correct to observe that it is redundant.
It's just the way that SSMS generates scripts.
Note that the script could be modified after it is generated. That first statement could be changed to use 'WITH NO CHECK', and that second statement would not be redundant.
The purpose of the first statement is to add the constraint.
The purpose of the second statement is to enable the constraint.
At least, that's the way I read the script. If I were manually running the statements one by one, I might get a "constraint already exists" exception, but that constraint might not be enabled.
I would still run the second statement, to ensure the existing constraint gets enabled.

Please explain the syntax the SQLServer uses to create a check constraint

When I right click on a default constraint and I ask SQL Server to create a CREATE script for it, it generates the following code:
ALTER TABLE [dbo].[tblEventTurnJudgeStartValues] WITH NOCHECK ADD CONSTRAINT [tblEventTurnJudgeStartValues_ExecutionToggle] CHECK (([ExecutionToggle]=(1) OR [ExecutionToggle]=(0) OR [ExecutionToggle]=(-1)))
GO
ALTER TABLE [dbo].[tblEventTurnJudgeStartValues] CHECK CONSTRAINT [tblEventTurnJudgeStartValues_ExecutionToggle]
For the record, I understand the first ALTER statement but I do not understand what the the second alter statement does. Tried to google the "CHECK CONSTRAINT" phrase but only got hits on the add constraint syntax.
Thanks.
Seth
update
Thanks Joe for your answer. Found this link which helps.
http://blog.sqlauthority.com/2009/11/12/sql-server-disable-check-constraint-enable-check-constraint/
I did not know that you could enable and disable constraints. Cool!
Seth
The first statement creates the constraint, but since it is created with NOCHECK, existing data is not validated at the time of creation.
The second statement simply turns the constraint on and is technically redundant.
Personally, I'd prefer the second statement be written with the WITH CHECK option, which will validate all existing data against the constraint and will prevent the constraint from becoming untrusted.
ALTER TABLE [dbo].[tblEventTurnJudgeStartValues] WITH CHECK CHECK CONSTRAINT [tblEventTurnJudgeStartValues_ExecutionToggle]

Unable to drop constraint in SQL server 2005, "Could not drop constraint. See previous errors"

I'm trying to drop a constraint on a DB table, something like:
ALTER TABLE MyTable drop CONSTRAINT FK_MyTable_AnotherTable
But the execution just runs and runs. If I stop it I see:
Msg 3727, Level 16, State 0, Line 2
Could not drop constraint. See previous errors.
Web search throws up various pages but note that the constraint is properly named and I am trying to remove it using the correct name
I was having the same issue on SQL Server 2008 R2, I solved my problem with below line hopefully it will work for someone else as well :)
Alter Table [Table Name]
DROP Column [Column Name]
Found a way to sort this, although I don't understand why it was necessary.
Have been able to drop the constraint by disabling it first:
ALTER MyTable NOCHECK CONSTRAINT FK_MyTable_AnotherTable
The drop then completes fine
Would still welcome any comments on the reason why this is necessary
Verify that you've not already dropped the constraint, like:
SELECT OBJECT_ID('FK_MyTable_AnotherTable')
If this returns null, your constraint no longer exists. That would explain the error message.
I had same problem.
The reason was that I made a mistake in my cursor statement, which was iterating some constraint I was to drop.
So this error occurred when the constraint was actually removed in the same transaction. Then I did a rollback and checked if it existed: it did (of course, after rollback!).
Check if it really exists at the moment of dropping.