views:

35

answers:

4

I need to import a lot of data into a sql server database. Some of this data was imported from long ago and much of it does not maintain referential integrity but I want all new data to. I can turn off the constraint checks prior to the import but how do it turn them back on only for data that will be added later? Is this possible or do I have to fix the historical data?

Thanks,

+2  A: 

As an ugly alternative, I suppose that you could have two tables -- one for old bad data, and one for new. Put the DRI constraints only on the new table. Then wrap them together with a UNION in a VIEW, so that other code can query them together as a single unit.

Chris Wuestefeld
+3  A: 

drop your FK constraints, add the data, add your FKs back with NOCHECK

Mike M.
BAd idea unless the importing only runs in single user mode. You are dropping the constraints for everyone not just your process. You could end up with even worse data this way.
HLGEM
Completely agree, the relationships are there for a reason and they should (almost always) be maintained. However, there are some rare situations where it's impossible and/or not worth the effort to go back and make the relationships work. Conversions from legacy systems come to mind.-EDIT, I meant to stick this under your post, not your comment to me.
Mike M.
The conversion from legacy is exactly what this is. However, there may be few enough of them that we can just fix the old data. If not, this will do. Thanks.
Jeff
+1  A: 

You can add a constraint that will check data only from that time forward, but if you try to update that row (as in an import or even through the user interface), it will hit the constraint and fail unless you fix the data. I strongly recommend you fix the data before adding constraints. It's bad data anyway and should be fixed. YOu might need to add a default record for UNKNOWN in the parent table if you have records that have a child id but no parent. Then change the refernce to the UNKNOWN record ID.

HLGEM
+1  A: 

use NOCHECK

example

CREATE TABLE CheckTbl (col1 int, col2 int);
GO


insert CheckTbl values(1,1)
insert CheckTbl values(2,1)

ALTER TABLE CheckTbl  WITH NOCHECK 
ADD CONSTRAINT chkRowCount CHECK (col1 > 1) ;
GO

-- will fail now
insert CheckTbl values(1,1)
SQLMenace