Reputation: 1
Can anyone help in converting string value in C# to bit equivalent in Sql. I'm trying to bulkcopy the values of a datatable into Sql table. All the values I've in the datatable are in string format. When I try to bulkcopy to SQL table I'm getting an error for bit datatype columns.Can anyone please post the C# code to convert string to bit type before I bulkcopy to SQL table.
Thanks, Vix
Upvotes: 0
Views: 25864
Reputation: 31
int a = Convert.ToInt32( row.ItemArray[5]);
bool b;
b = Convert.ToBoolean(a);
switch (a)
{
case 1:
b = true;
break;
case 0:
b = false;
break;
}
Upvotes: 1
Reputation: 432311
SQL Server will recognise "true" and "false" for the bit datatype. Also, zero stores zero, non-zero stores as "1".
Are you sending "true"
or true
?
If you get the same error with doubles (as per comments to other answers), then I suspect you are sending quotes.
Upvotes: 1
Reputation: 62929
If your strings are "true" and "false" (ignoring case and whitespace) this will work:
bool bit = bool.Parse(str);
If your strings are something else, you could use:
bool bit = !string.IsNullOrEmpty(str) &&
(str[0]=='Y' || str[0]=='y' || str[0]=='T' || str[0]=='t' || str[0]=='1');
SQL wants a bool value.
Upvotes: 5
Reputation: 60957
The bit
data type in SQL Server matches up to the bool
data type in C#. So just convert your strings to bool
s (using bool.Parse()
or your favorite alternative) and you should be set.
Upvotes: 0