I have a script which creates an entire database and inserts all records to a few dozen tables.
It works great, unless there is some issue during the processing, and a table gets left with IDENTITY\_INSERT ON, when the script fails during insertion and before it can be set to OFF again.

When this happens, the script automatically fails when attempting to run it again, with the error "IDENTITY\_INSERT is already ON for table xx" as we go into the insertion for the first table.

As a failsafe I would like to make sure that IDENTITY\_INSERT is set to OFF for all tables, before running the rest of the processing in the setup script. 

As an alternative, we could perhaps close the MS SQL connection and open it again, which, as I understand it, would clear all IDENTITY\_INSERT values for the connection session.

What's the best way to do this, and prevent the "already on" errors?