Recipe 1.6 · C#
Bulk Loads with SqlBulkCopy and Table-Valued Parameters
Problem
A nightly import inserts a supplier's price file, 200,000 rows, one INSERT per row. Each insert is a network round trip and a log flush. The job that should take seconds takes most of an hour. A related problem shows up at the other end of the scale: passing a list of 300 IDs to a query, usually by building a comma-separated string.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: one round trip per row.
foreach (var row in rows)
{
SqlCommand cmd = new SqlCommand(
"INSERT INTO PriceImport (Sku, Price, EffectiveDate) " +
"VALUES ('" + row.Sku + "', " + row.Price + ", '" +
row.EffectiveDate + "')", conn);
cmd.ExecuteNonQuery();
}
On top of the speed problem, this inserts prices formatted with the server's current culture. On a machine set to a European culture, 12.50 becomes 12,50 and the statement fails.
The improved recipe
The table-valued parameter type the second class uses:
CREATE TYPE dbo.IntList AS TABLE
(
Value INT NOT NULL PRIMARY KEY
);
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Microsoft.Data.SqlClient.Server;
namespace ImproveCode.Data;
public sealed record PriceImportRow(
string Sku, decimal Price, DateTime EffectiveDate);
public sealed class PriceImporter(IDbConnectionFactory db)
{
public async Task LoadAsync(
IEnumerable<PriceImportRow> rows,
CancellationToken ct = default)
{
var table = new DataTable();
table.Columns.Add("Sku", typeof(string));
table.Columns.Add("Price", typeof(decimal));
table.Columns.Add("EffectiveDate", typeof(DateTime));
foreach (PriceImportRow r in rows)
{
table.Rows.Add(r.Sku, r.Price, r.EffectiveDate);
}
await using var connection = await db.OpenAsync(ct);
using var bulk = new SqlBulkCopy(
connection,
SqlBulkCopyOptions.CheckConstraints
| SqlBulkCopyOptions.TableLock,
externalTransaction: null)
{
DestinationTableName = "staging.PriceImport",
BatchSize = 5_000,
BulkCopyTimeout = 300
};
foreach (DataColumn column in table.Columns)
{
bulk.ColumnMappings.Add(
column.ColumnName, column.ColumnName);
}
await bulk.WriteToServerAsync(table, ct);
}
}
public sealed record ProductName(int ProductId, string Name);
public sealed class ProductQueries(IDbConnectionFactory db)
{
private const string ByIdsSql = """
SELECT p.ProductId, p.Name
FROM dbo.Product AS p
JOIN @Ids AS i ON i.Value = p.ProductId;
""";
public async Task<List<ProductName>> ByIdsAsync(
IEnumerable<int> ids, CancellationToken ct = default)
{
await using var connection = await db.OpenAsync(ct);
await using var command = new SqlCommand(ByIdsSql, connection);
command.Parameters.Add(IntList("@Ids", ids));
await using var reader = await command.ExecuteReaderAsync(ct);
var results = new List<ProductName>();
while (await reader.ReadAsync(ct))
{
results.Add(new ProductName(
reader.GetInt32(0), reader.GetString(1)));
}
return results;
}
public static SqlParameter IntList(
string name, IEnumerable<int> values)
{
var meta = new SqlMetaData("Value", SqlDbType.Int);
var records = new List<SqlDataRecord>();
foreach (int value in values.Distinct())
{
var record = new SqlDataRecord(meta);
record.SetInt32(0, value);
records.Add(record);
}
return new SqlParameter(name, SqlDbType.Structured)
{
TypeName = "dbo.IntList",
Value = records.Count == 0 ? null : records
};
}
}
How it works
SqlBulkCopy streams rows to the server using the same bulk-load protocol as the bcp utility. Rows are minimally logged where the recovery model and table allow it, and the whole load is a handful of round trips. BatchSize commits every 5,000 rows so the log does not grow with one enormous transaction, and TableLock lets the server take a bulk update lock rather than row locks.
Two options matter. By default SqlBulkCopy skips check constraints and does not fire triggers; CheckConstraints turns constraint checking back on. Explicit ColumnMappings match columns by name. Without them, columns are matched by position, and adding a column to the staging table silently shifts data.
The values travel as typed data, not text, so culture-specific decimal separators and date formats stop mattering.
Table-valued parameters solve the smaller problem. The IntList method turns any sequence of integers into a structured parameter of the type dbo.IntList, and the query joins to it like a table. The primary key on the type removes duplicates and gives the optimizer a unique key, which is why the method calls Distinct() first.
Variations and pitfalls
- Load to staging, then merge. I bulk load into a staging table with no foreign keys, validate with set-based SQL, then move the rows into the real table with one
INSERT ... SELECTor an upsert from Chapter 2. A bad file then fails in staging, not halfway through production data. - Empty TVPs. An empty list of
SqlDataRecordthrows. Passingnullsends an empty table, which is what the method does when the input is empty. - Very large loads. A
DataTableholds every row in memory. For millions of rows, pass anIDataReadertoWriteToServerAsyncinstead, either a reader from another database or a smallDbDataReaderover your file. TheFastMemberpackage'sObjectReaderis a common shortcut. - TVPs and procedures. A TVP parameter in a procedure must be declared
READONLY:@Ids dbo.IntList READONLY. - Changing a TVP type requires dropping every procedure that uses it first. Name types for what they hold (
dbo.IntList,dbo.SkuPriceList) and change them rarely.