简体   繁体   中英

SQL Server stored procedure to return failed records from sql bulk insertion

I have a stored procedure with following code

INSERT INTO  contribution(
                eligibility_id, 
                earnings, 
                member, 
                employer, 
                begin_date, 
                end_date,
                active,
                os_user_name,
                date_modified,
                sql_user_name,
                date_created,
                eligible_fl
    )

    select
            eligibility_id, 
                earnings, 
                member, 
                employer, 
                begin_date, 
                end_date,
                active,
                os_user_name,
                date_modified,
                sql_user_name,
                date_created,
                eligible_fl
     from @ContributionIns

Is it possible to return failed records or inserted records from this stored procedure?

You can use the OUTPUT clause to return inserted records.

INSERT INTO [Table] (<columns>) 
OUTPUT inserted.* 
SELECT <columns> 
FROM @ContributionIns;

You cannot have a mixture of failed and successful inserts in a single insert statement, so either all of your records are inserted, or all of them failed. As such you could use a try/catch block:

BEGIN TRY
    INSERT INTO [Table] (<columns>) 
    OUTPUT 'Success' AS [Status], inserted.* 
    SELECT <columns> 
    FROM @ContributionIns;
END TRY
BEGIN CATCH

    SELECT  'Failed' AS [Status], 
            <columns> 
    FROM    @ContributionIns;

END CATCH

Although I personally don't like this approach in SQL Server, I think 99% of the time you are better off letting the error propagate, and living with the knowledge that if you get an error all of the records failed.

Your SQL statement is a single statement, so it will not insert only those records that "succeed". Either then entire statement will fail and no records are inserted or it will succeed and ALL records are inserted. Based on your query it's hard to know what would fail, other than violation of primary/foreign keys or unique indices.

In you expect that some records would fail based on some condition (violation of constraints, etc.) then you'll need to check for those violations upfront and ONLY try to insert records that you are reasonably certain will succeed.

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