vix
vix

Reputation: 1

Converting String to bit before inserting into the database

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

Answers (4)

sumitha.v.r
sumitha.v.r

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

gbn
gbn

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

Ray Burns
Ray Burns

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

Daniel Pryden
Daniel Pryden

Reputation: 60957

The bit data type in SQL Server matches up to the bool data type in C#. So just convert your strings to bools (using bool.Parse() or your favorite alternative) and you should be set.

Upvotes: 0

Related Questions