Don Bernstein (12/22/2010)
SET IDENTITY_INSERT IDDemo OFF
EXEC ('SET IDENTITY_INSERT IDDemo ON')
INSERT IDDemo (pk_ID, Textdata) Values (4, 'This fails')
When I run it (sql2005), I get an error: Cannot insert explicit value for identity column...
Only one row is returned.
IDENTITY_INSERT is a session level option, and essentially anything you run with with EXEC runs in a new session. So like the other people said, and provided examples for, you would need to put anything that relies on the IDENTITY_INSERT option into the dynamic SQL, but make sure you watch out for SQL injections, since to set the IDENTITY_INSERT option requires a fair amount of privileges. Of course to be of any value your INSERT would have to by dynamic as well, since I assume that you want to insert into the table passed as a parameter.
Another option, if the set of tables is know, is to use IF statements to turn the option on for the correct table and INSERT the record. Yes, it is more code to manage but you wouldn't have to worry about SQL injection.