|
|||||||||||
|
Home > Posts > Creating a Validating DataReader for SqlBulkCopyThe ValidatingDataReader class is intended to provide as detailed error messages as possible for SqlBulkCopy in both invalid mappings and when data is too large for the destination columnDownload ValidatingDataReader.cs.txt (Right Click->Save Target As...). The most frustrating thing about working with SqlBulkCopy is the lack of useful error messages:
It even gives you suggestions in the case where capitalization may be a factor and if you choose to, giving you the opportunity to truncate offending data to prevent an exception. Compare the previous error messages to these:
using (CsvDataReader reader = CsvDataReader.Parse("id,name\r\n1,Bruce Dunwiddie")) using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Database)) using (SqlBulkCopy bcp = new SqlBulkCopy(conn)) { conn.Open(); using (SqlCommand createTable = new SqlCommand(@" IF EXISTS ( SELECT * FROM sys.tables t INNER JOIN sys.schemas s ON s.schema_id = t.schema_id WHERE t.[name] = 'Test' AND s.[name] = 'dbo' ) BEGIN DROP TABLE dbo.Test; END CREATE TABLE dbo.Test ( [id] INT, [name] VARCHAR(10) -- this is obviously too short );", conn)) { createTable.ExecuteNonQuery(); } reader.Settings.HasHeaders = true; reader.Columns.Add("int"); reader.Columns.Add("varchar"); bcp.DestinationTableName = "dbo.Test"; bcp.ColumnMappings.Add("id", "[id]"); bcp.ColumnMappings.Add("name", "[name]"); using (ValidatingDataReader validator = new ValidatingDataReader(reader, conn, bcp)) { bcp.WriteToServer(validator); } }Please send any questions or comments to Bruce Dunwiddie. |
||||||||||
|
|||||||||||