Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 283
  • Last Modified:

NoCheck Constraint

This is more a question to make sure I am doing this right.

I have a table, let's call it "clicks"

click_id int PK
product_id int  

I am trying to correct an error from a previous time where the product_id was set to default to zero.  I have a table of "products" and need to set the product_id to a null default in "clicks", remove the default constraint of 0 from "clicks" and then foreign key product_id in "clicks" to product_id in "products".

All is well with removing the constraint.  However, I have 50,000,000 rows of "clicks" historical data with a 0 in the product_id.  The job of sanitizing this data to update all the 0's to null is too big for now.  

Question - If I create the FK with a NOCHECK Constraint would I have the correct FK structure going forward and have the DB basically ignore the legacy data (for now)?

Later, I can run the scripts to fix the legacy data and then alter the FK to be correct and check the constraint.

Am I on the right path?
0
ccleebelt
Asked:
ccleebelt
  • 2
2 Solutions
 
QuinnDexCommented:
a defualt constraint works on newly added or up dated data, existing data will not be checked by it unles you up date it, in which case you can add a trigger to change the 0 to a null value thus reducing the update task ahead
0
 
ccleebeltAuthor Commented:
So basically, if I put the WITH NOCHECK ADD CONSTRAINT in the alter script when creating the FK the relationship it is bound going forward, but legacy data would be ignored then eh?

In other words, I get the FK between the tables for data from this point forward, but the legacy data would just not perform as well?
0
 
Scott PletcherSenior DBACommented:
Yes, that's basically it: if you add the constraint with NOCHECK, then until/unless you update the product_id column in the "clicks" table, it won't be checked.  But any newly inserted row will be.

Rather than a trigger, I'd just start UPDATEing "clicks" rows in batches, setting any product_id = 0 to NULL.  A NULL value in a column will cause the fk check to be ignored/bypassed.
0
 
ccleebeltAuthor Commented:
yep, the plan is to get this going and then once all the product_ids are set to null (in batches) run the ALTER TABLE clicks WITH CHECK CHECK CONSTRAINT ALL so it is trusted.
0

Featured Post

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now