SQL - Cannot add check constraint without checking the existing rows - sql

I need to modify an existing constraint. I read on multiple topic that it's impossible, we need to delete and recreate it. So I've delete it and rewrote it. When trying to save it in SQL Server Management studio I got this error message :
Unable to add constraint chk_AnneeNaissance. The ALTER TABLE statement conflicted with the CHECK CONSTRAINT chk_AnneeNaissance.
I know that I have some row in my database not fulfilling this constraints but I want to add it for the next insert.
I've looked around and I found that I need to do the command myself with a NOCHECK so I'm trying this command :
ALTER TABLE [GENERAL].[dbo].[Base] WITH NOCHECK ADD CONSTRAINT chk_AnneeNaissance
But I have this error :
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'chk_AnneeNaissance'.
Can someone help me writing the right command?

ALTER TABLE [ERI_COPY_20170315].[dbo].[Base] WITH NOCHECK
ADD CONSTRAINT chk_AnneeNaissance
CHECK (
[Année de naissance] IS NOT NULL AND
[Année de naissance]>=([Date de valeur]-(80)) AND
[Année de naissance]<=([Date de valeur]-(15)) AND
len([Année de naissance])=(4)
)
It works perfectly. Thanks James Z ! I didn't know where I should put my constraints code.

Related

Cannot drop/alter column in SQL Azure

As the title says, I cannot drop or alter a column in SQL Azure. I wanted to change its datatype from int to tinyint. I did specify tinyint, but it seems Azure overrode that.
I've tried via the Management Console as well as from SSMS.
I found the following SO question, but importantly, my column is not a primary/foreign key and is not even used in an index.
SQL Azure - Could not able to alter column type
In Aure Management Console, I get the following error
<?xml version="1.0" encoding="utf-8"?><m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><m:code>InternalError:7752a6bb-a244-f1a0-221b-b9c482ae6680</m:code><m:message xml:lang="en-US">An error was encountered while applying the changes.
An exception occurred while executing the Transact-SQL statement: ALTER TABLE [dbo].[xxxxx] DROP COLUMN [EmailFrequency2].
The object 'ColumnDefault_b0898c7d-0fb6-4466-8894-1325eb8c4efd' is dependent on column 'EmailFrequency2'.
ALTER TABLE DROP COLUMN EmailFrequency2 failed because one or more objects access this column.</m:message></m:error>
I did try googling "InternalError:7752a6bb-a244-f1a0-221b-b9c482ae6680" but got zero hits.
I've tried disable constraints when attempting to alter the table (to change the datatype from int to tinyint):
ALTER TABLE [dbo].[xxxxx] NOCHECK CONSTRAINT ALL
ALTER TABLE [dbo].[xxxxx] ALTER COLUMN [EmailFrequency] TINYINT NULL
ALTER TABLE [dbo].[xxxxx] NOCHECK CONSTRAINT ALL
But I get basically the same error:
Msg 5074, Level 16, State 1, Line 2
The object 'ColumnDefault_871cbb52-f294-4a57-9c51-b8fd435d0d59' is dependent on column 'EmailFrequency'.
Msg 4922, Level 16, State 9, Line 2
ALTER TABLE ALTER COLUMN EmailFrequency failed because one or more objects access this column.
I can't find any reference to the ColumnDefault_xxxx-GUID-xxx object anywhere
Can anyone suggest how I could get around this constraint? I was able to rename the table, but not drop it or change the datatype.
The default value is a constraint you have in place, you have to delete it first:
ALTER TABLE xxxxx DROP CONSTRAINT <name of your default here>
I used code first migrations, and in my case, I was trying to make a property of a class not null by using [Required] annotation above the property. This kept giving me the JSON response "An error has occurred" when I tried to reach my endpoints.
After some time I realized I had records in that particular table, which had no value for the property I was trying to make not null, hence the error. Stupid mistake. I hope I can save someone from hours of googling. Haha.

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]

Problem with an SQL statement

I'm having a problem with an SQL statement.
I want to activate a "ON UPDATE CASCADE" behavior for a foreign key in a table with this statement :
ALTER TABLE "DB"."RECORD" ADD CONSTRAINT "RECORD_PT_OUTIL_FK1" FOREIGN KEY ("CDE_PO")
REFERENCES "DB"."PT_OUTIL" ("CDE_PO") ON UPDATE CASCADE ENABLE;
But when i run the statement in Oracle Developer, i just get this error message : "ORA-00905 : missing keyword"
I can't find what could be this missing keyword, i tried several changes but always the same error occurs.
I reuse a code generated by Oracle Developer it self and just modify it with what i want.
This is the generated code :
ALTER TABLE "DB"."RECORD" ADD CONSTRAINT "RECORD_PT_OUTIL_FK1" FOREIGN KEY ("CDE_PO")
REFERENCES "DB"."PT_OUTIL" ("CDE_PO") ON DELETE CASCADE DISABLE;
See, i just change the end of it.
So what's the matter here ? Am i missing something ? (please don't bash if it's something obvious :) )
Thx !
Oracle does not support the ON UPDATE clause for foreign keys.
See the description of the REFERENCES clause in the manual:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/clauses002.htm#CJAIHHGC
Try by removing the DISABLE/ ENABLE at the end of your command
As per the ADD CONSTRAINT reference, there doesnt seem to be any "Enable / Disable" as part of the command.
I think it is something that your Oracle Developer is adding at the end (it being part of Oracle Syntax) and it might be causing the problem!!

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.

Modify unique constraint in Oracle

I need to update an existing constraint in Oracle database to add a new column there.
ALTER TABLE MY_PARTNER_DETAILS
MODIFY CONSTRAINT UQ_MY_PARTNER_DETAILS
UNIQUE(PARTNER_CODE,PGOOD_CODE,SITE_CODE,PARTNER_PLACEMENT,PARTNER_PARTICIPATION)
Gives the error:
Error at line 1
ORA-00933: SQL command not properly ended
What's the problem with that?
You should drop and recreate the constraint. modify constraint allows you to change constraint's state not definition.
See: Oracle Docs