Search code examples
sqlsql-serverssmssql-insertopenrowset

SQL Server continue series of inserts from Select statements despite errors(?)


I have a large file of SQL statements that are lined up as follows:

 INSERT INTO [table here]
    SELECT [columns]
    FROM OPENROWSET(xlsx tab 1)

INSERT INTO [table here]
    SELECT [columns]
    FROM OPENROWSET(xlsx tab 2)

... etc etc...

The problem is that sometimes XLSX tab #2 (or 22) does not exist and may cause an error and the entire series of statements fails.

Is there a way to get each statement to execute as though they were their own query or ignore the error and continue?

Thanks!


Solution

  • Error Handling in SQLServer is tricky.There some errors that abort entire batch,some which abort entire session,errors which abort session can't be caught and can't be retried from SSMS itself

    In your case,if you want one insert ,not to be affected by another..Try separating them with BATCH SEPARATOR GO

    INSERT INTO 
    SELECT 
    GO
    
    INSERT
    SELECT
    GO
    

    Reference and further reading :
    Error and Transaction Handling in SQL Server