Vijeeshkumar vofox
Vijeeshkumar vofox

Reputation: 641

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?

Upvotes: 1

Views: 804

Answers (2)

D Stanley
D Stanley

Reputation: 152566

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.

Upvotes: 1

GarethD
GarethD

Reputation: 69769

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.

Upvotes: 4

Related Questions