简体   繁体   中英

Foreign key Constraints - Writing to Error Table - SQL Server 2008

I am new to SQL Server. I have a Batch process that loads data into my stage tables. I have some foreign Keys on that table. I want to dump all the foreign key errors encountered while loading into a error table. How do I do that?

Thanks New Novice

Use SSIS to load the data. Records which fail validation can be sent off to a an exception table.

One approach would be to load the data into a temporary table which has no FK constraints, remove the bad records (that violate the FK constraints), then move the data from the temp table into the stage table. If you have lots of FKs on your table this will probably be a bit tedious, so you would probably want to automate the process.

Here's some pseudo-code to show what I mean...

    -- First put the raw data into MyTempTable

    -- Find the records that are "bad" -- you can SELECT INTO a "bad records" table
    -- for later inspection if you want...
    SELECT * 
    INTO #BadRecords
    FROM MyTempTable
    WHERE ForeignKeyIDColumn NOT IN
    (
        SELECT ID FROM ForeignKeyTable
    )
    -- Remove the bad records now
    DELETE
    FROM MyTempTable
    WHERE ForeignKeyIDColumn NOT IN
    (
        SELECT ID FROM ForeignKeyTable
    )
    -- Now the data is "clean" (won't violate the FK) so you can insert it 
    -- from MyTempTable into the stage table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM