<p>I am hitting some performance bottlenecks with my C# client inserting bulk data into a SQL Server 2005 database and I'm looking for ways in which to speed up the process.</p>

<p>I am already using the SqlClient.SqlBulkCopy (which is based on TDS) to speed up the data transfer across the wire which helped a lot, but I'm still looking for more.</p>

<p>I have a simple table that looks like this: </p>

<pre><code> CREATE TABLE [BulkData](
 [ContainerId] [int] NOT NULL,
 [BinId] [smallint] NOT NULL,
 [Sequence] [smallint] NOT NULL,
 [ItemId] [int] NOT NULL,
 [Left] [smallint] NOT NULL,
 [Top] [smallint] NOT NULL,
 [Right] [smallint] NOT NULL,
 [Bottom] [smallint] NOT NULL,
 CONSTRAINT [PKBulkData] PRIMARY KEY CLUSTERED 
 (
  [ContainerIdId] ASC,
  [BinId] ASC,
  [Sequence] ASC
))
</code></pre>

<p>I'm inserting data in chunks that average about 300 rows where ContainerId and BinId are constant in each chunk and the Sequence value is 0-n and the values are pre-sorted based on the primary key.  </p>

<p>The %Disk time performance counter spends a lot of time at 100% so it is clear that disk IO is the main issue but the speeds I'm getting are several orders of magnitude below a raw file copy.</p>

<p>Does it help any if I:</p>

<ol>
<li>Drop the Primary key while I am doing the inserting and recreate it later</li>
<li>Do inserts into a temporary table with the same schema and periodically transfer them into the main table to keep the size of the table where insertions are happening small</li>
<li>Anything else?</li>
</ol>

<p>--
Based on the responses I have gotten, let me clarify a little bit:</p>

<p>Portman: I'm using a clustered index because when the data is all imported I will need to access data sequentially in that order.  I don't particularly need the index to be there while importing the data.  Is there any advantage to having a nonclustered PK index while doing the inserts as opposed to dropping the constraint entirely for import?</p>

<p>Chopeen:  The data is being generated remotely on many other machines (my SQL server can only handle about 10 currently, but I would love to be able to add more).  It's not practical to run the entire process on the local machine because it would then have to process 50 times as much input data to generate the output.</p>

<p>Jason: I am not doing any concurrent queries against the table during the import process, I will try dropping the primary key and see if that helps.</p>

[{'answer_id': 24204, 'author': 'jason saldo', 'author_id': 1293, 'author_profile': 'https://Stackoverflow.com/users/1293', 'pm_score': -1, 'selected': False, 'text': '<p>Yes your ideas will help.<br>\nLean on option 1 if there are no reads happening while your loading.<br>\nLean on option 2 if you destination table is being queried during your processing.</p>\n\n<p>@Andrew<br>\nQuestion.  Your inserting in chunks of 300.  What is the total amount your inserting?  SQL server should be able to handle 300 plain old inserts very fast.</p>\n'}, {'answer_id': 24214, 'author': 'dguaraglia', 'author_id': 2384, 'author_profile': 'https://Stackoverflow.com/users/2384', 'pm_score': 3, 'selected': False, 'text': '<p>Have you tried using transactions?</p>\n\n<p>From what you describe, having the server committing 100% of the time to disk, it seems you are sending each row of data in an atomic SQL sentence thus forcing the server to commit (write to disk) every single row.</p>\n\n<p>If you used transactions instead, the server would only commit <em>once</em> at the end of the transaction.</p>\n\n<p>For further help: What method are you using for inserting data to the server? Updating a DataTable using a DataAdapter, or executing each sentence using a string?</p>\n'}, {'answer_id': 24224, 'author': 'Portman', 'author_id': 1690, 'author_profile': 'https://Stackoverflow.com/users/1690', 'pm_score': 4, 'selected': False, 'text': '<p>You\'re already using <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx" rel="noreferrer">SqlBulkCopy</a>, which is a good start.</p>\n\n<p>However, just using the SqlBulkCopy class does not necessarily mean that SQL will perform a bulk copy. In particular, there are a few requirements that must be met for SQL Server to perform an efficient bulk insert.</p>\n\n<p>Further reading:</p>\n\n<ul>\n<li><a href="http://msdn.microsoft.com/en-us/library/ms190422.aspx" rel="noreferrer">Prerequisites for Minimal Logging in Bulk Import</a></li>\n<li><a href="http://msdn.microsoft.com/en-us/library/ms190421.aspx" rel="noreferrer">Optimizing Bulk Import Performance</a></li>\n</ul>\n\n<p>Out of curiosity, why is your index set up like that? It seems like ContainerId/BinId/Sequence is <strong>much</strong> better suited to be a nonclustered index. Is there a particular reason you wanted this index to be clustered?</p>\n'}, {'answer_id': 24305, 'author': 'travis', 'author_id': 1414, 'author_profile': 'https://Stackoverflow.com/users/1414', 'pm_score': 1, 'selected': False, 'text': '<p>I think that it sounds like this could be done using <a href="http://msdn.microsoft.com/en-us/library/ms141026.aspx" rel="nofollow noreferrer">SSIS packages</a>. They\'re similar to SQL 2000\'s DTS packages. I\'ve used them to successfully transform everything from plain text CSV files, from existing SQL tables, and even from XLS files with 6-digit rows spanned across multiple worksheets. You could use C# to transform the data into an importable format (CSV, XLS, etc), then have your SQL server run a scheduled SSIS job to import the data.</p>\n\n<p>It\'s pretty easy to create an SSIS package, there\'s a wizard built-into SQL Server\'s Enterprise Manager tool (labeled "Import Data" I think), and at the end of the wizard it gives you the option of saving it as an SSIS package. There\'s a bunch more info <a href="http://technet.microsoft.com/en-us/sqlserver/bb671392.aspx" rel="nofollow noreferrer">on Technet</a> as well.</p>\n'}, {'answer_id': 24449, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.databasejournal.com/features/mssql/article.php/3391761" rel="nofollow noreferrer">BCP</a> - it\'s a pain to set up, but it\'s been around since the dawn of DBs and it\'s very very quick.</p>\n\n<p>Unless you\'re inserting data in that order the 3-part index will really slow things.  Applying it later will really slow things too, but will be in a second step.</p>\n\n<p>Compound keys in Sql are always quite slow, the bigger the key the slower.</p>\n'}, {'answer_id': 24577, 'author': 'Portman', 'author_id': 1690, 'author_profile': 'https://Stackoverflow.com/users/1690', 'pm_score': 3, 'selected': False, 'text': '<p>My guess is that you\'ll see a dramatic improvement if you change that index to be <strong>nonclustered</strong>. This leaves you with two options:</p>\n\n<ol>\n<li>Change the index to nonclustered, and leave it as a heap table, without a clustered index</li>\n<li>Change the index to nonclustered, but then add a surrogate key (like "id") and make it an identity, primary key, and clustered index</li>\n</ol>\n\n<p>Either one will speed up your inserts <strong>without</strong> noticeably slowing down your reads. </p>\n\n<p>Think about it this way -- right now, you\'re telling SQL to do a bulk insert, but then you\'re asking SQL to reorder the entire table every table you add anything. With a nonclustered index, you\'ll add the records in whatever order they come in, and then build a separate index indicating their desired order. </p>\n'}, {'answer_id': 242197, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m not really a bright guy and I don\'t have a lot of experience with the SqlClient.SqlBulkCopy method but here\'s my 2 cents for what it\'s worth.  I hope it helps you and others (or at least causes people to call out my ignorance ;).</p>\n\n<p>You will never match a raw file copy speed unless your database data file (mdf) is on a separate physical disk from your transaction log file (ldf).  Additionally, any clustered indexes would also need to be on a separate physical disk for a fairer comparison.</p>\n\n<p>Your raw copy is not logging or maintaining a sort order of select fields (columns) for indexing purposes.</p>\n\n<p>I agree with Portman on creating a nonclustered identity seed and changing your existing nonclustered index to a clustered index.</p>\n\n<p>As far as what construct you\'re using on the clients...(data adapter, dataset, datatable, etc).  If your disk io on the server is at 100%, I don\'t think your time is best spent analyzing client constructs as they appear to be faster than the server can currently handle.</p>\n\n<p>If you follow Portman\'s links about minimal logging, I wouldn\'t think surrounding your bulk copies in transactions would help a lot if any but I\'ve been wrong many times in my life ;)</p>\n\n<p>This won\'t necessarily help you right now but if you figure out your current issue, this next comment might help with the next bottleneck (network throughput) - especially if it\'s over the Internet...</p>\n\n<p>Chopeen asked an interesting question too.  How did you determine to use 300 record count chunks to insert?  SQL Server has a default packet size (I believe it is 4096 bytes) and it would make sense to me to derive the size of your records and ensure that you are making efficient use of the packets transmitting between client and server.  (Note, you can change your packet size on your client code as opposed to the server option which would obviously change it for all server communications - probably not a good idea.)  For instance, if your record size results in 300 record batches requiring 4500 bytes, you will send 2 packets with the second packet being mostly wasted.  If batch record count was arbitrarily assigned, it might make sense to do some quick easy math.</p>\n\n<p>From what I can tell (and remember about data type sizes) you have exactly 20 bytes for each record (if int=4 bytes and smallint=2 bytes).  If you are using 300 record count batches, then you are trying to send 300 x 20 = 6,000 bytes (plus I\'m guessing a little overhead for the connection, etc).  You might be more efficient to send these up in 200 record count batches (200 x 20 = 4,000 + room for overhead) = 1 packet.  Then again, your bottleneck still appears to be the server\'s disk io.</p>\n\n<p>I realize you\'re comparing a raw data transfer to the SqlBulkCopy with the same hardware/configuration but here\'s where I would go also if the challenge was mine:</p>\n\n<p>This post probably won\'t help you anymore as it\'s rather old but I would next ask what your disk\'s RAID configuration is and what speed of disk are you using?  Try putting the log file on a drive that uses RAID 10 with a RAID 5 (ideally 1) on your data file.  This can help reduce a lot of spindle movement to different sectors on the disk and result in more time reading/writing instead of the unproductive "moving" state.  If you already separate your data and log files, do you have your index on a different physical disk drive from your data file (you can only do this with clustered indexes).  That would allow for not only concurrently updating logging information with data inserting but would allow index inserting (and any costly index page operations) to occur concurrently.</p>\n'}, {'answer_id': 2899468, 'author': 'JohnB', 'author_id': 287311, 'author_profile': 'https://Stackoverflow.com/users/287311', 'pm_score': 5, 'selected': False, 'text': '<p>Here\'s how you can disable/enable indexes in SQL Server:</p>\n\n<pre><code>--Disable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users DISABLE\nGO\n--Enable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users REBUILD</code></pre>\n\n<p>Here are some resources to help you find a solution:</p>\n\n<p><a href="http://weblogs.sqlteam.com/mladenp/archive/2006/07/17/10634.aspx" rel="noreferrer">Some bulk loading speed comparisons</a></p>\n\n<p><a href="http://www.sqlteam.com/article/use-sqlbulkcopy-to-quickly-load-data-from-your-client-to-sql-server" rel="noreferrer">Use SqlBulkCopy to Quickly Load Data from your Client to SQL Server</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/aa178096(SQL.80).aspx" rel="noreferrer">Optimizing Bulk Copy Performance</a></p>\n\n<p>Definitely look into NOCHECK and TABLOCK options:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/ms187373.aspx" rel="noreferrer">Table Hints (Transact-SQL)</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/ms174335.aspx" rel="noreferrer">INSERT (Transact-SQL)</a></p>\n'}, {'answer_id': 73020670, 'author': 'Ashish Babu', 'author_id': 19571159, 'author_profile': 'https://Stackoverflow.com/users/19571159', 'pm_score': 0, 'selected': False, 'text': "<p><strong>Still facing the issue? Try this one too.</strong></p>\n<ul>\n<li>Check the <strong>database configuration( Memory &amp; Processor ).</strong></li>\n<li>For bulky data's , I would suggest the <strong>Memory of at least 16GB</strong> and <strong>Processor of 16</strong></li>\n</ul>\n"}]
['https://Stackoverflow.com/questions/24200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1948/']