views:

1885

answers:

3

In my eternal saga to insert 1.4 million rows of data from a SQL script, I've written a basic WinForms app that takes each line of the script and executes it individually.

However, because the original script contained

SET IDENTITY_INSERT [Table] OFF

and SET is a session-wide command, this setting is getting lost on every SQL call, meaning that each line is failing. Is there a way to set IDENTITY_INSERT off for the whole table, database-wide just so I can make these individual calls without them failing? Or perhaps I can tell it to ignore the identity specification by appending a command to each line?

+3  A: 

BULK INSERT won't work for you? Or the SQL Server Import/Export Wizard (here or here)? I know import/export can turn off identity insert for the whole import. I'm reasonably certain you can do it just prior to BULK INSERT

tvanfosson
You may also want to look at the bcp utility for doing this, it is designed specifically for this task.http://msdn.microsoft.com/en-us/library/ms162802.aspxThere is a command-line option for bcp to override the identity column with a specified file from your import data.
esarjeant
I ended up having to convert my SQL script to a flat tab-delimited file, and then using bcp to import that. That was a lot more hassle than it should have been!
tags2k
A: 

I believe that IDENTITY INSERT can only be overridden one table at a time, per session.

You will have to maybe batch up 2 or 300 insert statements at a time and precede each batch with the ident insert.

so the app will execute a block like this....

SET IDENTITY_INSERT [Table] OFF;
INSERT INTO TABLE VALUES (1, 'a');
INSERT INTO TABLE VALUES (2, 'b');
INSERT INTO TABLE VALUES (3, 'c');
INSERT INTO TABLE VALUES (4, 'd');
INSERT INTO TABLE VALUES (5, 'e');
SET IDENTITY_INSERT [Table] ON;
StingyJack
A: 

Is anything else going to be accessing/inserting to the table while this is 1.4 million insert job is going on.

If not, you could simply Disable the Identity on the PK column for the duration of the job?

Eoin Campbell