This seems like a duplicate question. But as I searched & viewed the related questions & answers, i still can't find the answer.
I am writing a loader program which imports data records from CSV file to a database table. Here is the demo.
The database table is something as below:
use Test;
create table BoolTest (Name varchar(20) not null, IsValid bit not null);
insert into BoolTest (Name, IsValid) values('xx', 1);
insert into BoolTest (Name, IsValid) values('yy', 0);
The loader program is like:
class Program
{
static void Main(string[] args)
{
var csvFileContent = "Name,IsValid\r\naa,true\r\nbb,false";
var csvLines = csvFileContent.Split(new String[] { "\r\n" }, StringSplitOptions.None);
var columnNames = csvLines[0].Split(',');
var table = new DataTable();
foreach (var columnName in columnNames)
{
table.Columns.Add(new DataColumn(columnName));
}
for (var n = 1; n < csvLines.Length; ++n)
{
var line = csvLines[n];
var values = line.Split(',');
table.Rows.Add(values);
}
var connectionString = "Data Source=localhost;Initial Catalog=Test;Integrated Security=True";
using (var bulkCopy = new SqlBulkCopy(connectionString)) {
bulkCopy.DestinationTableName = "BoolTest";
bulkCopy.ColumnMappings.Add("Name", "Name");
bulkCopy.ColumnMappings.Add("IsValid", "IsValid");
bulkCopy.WriteToServer(table);
}
Console.WriteLine("Done");
Console.Read();
}
}
Everything is fine above.
But the problem is the CSV file is from 3rd party and the values for column 'IsValid' is 0 or 1 as below
Name,IsValid
aa,1
bb,0
When the loader program tries to load this CSV file, bulkCopy.WriteToServer(table) will throw out exception
The sql server I am using is Sql server 2014.
Any help will be appreciated. Thanks.
--- update ---
Thanks guys for the solutions. I will try to manually change 0/1 to false/true in loader program. But still want to know whether there is easy fix (like changing settings in SQL Server or SqlBulkCopy) for this issue.
I also tried sql in Sql Server Management Studio like
insert into BoolTest (Name, IsValid) values('aa', 1); -- this works as we expected
insert into BoolTest (Name, IsValid) values('aa', '1'); -- this also works to my surprise
Both works well. But not sure why SQL server rejects the bulk copy when the IsValid value is 0 or 1. And when we show the table data with 'select', the value for IsValid is actually 0 or 1.