Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a varchar column to bit column in SQL SERVER

Flag1 is a varchar column with values "true" and "false". I need to convert this into bit column.

When I try to do this:

Convert(Bit,Flag1)

it shows an error

Msg 245, Level 16, State 1, Line 2
Syntax error converting the varchar value 'False' to a column of data type bit.
like image 987
user1254579 Avatar asked Mar 13 '14 15:03

user1254579


People also ask

How do I create a bit column in SQL Server?

To create a table with BIT column: CREATE TABLE table_name ( bit_column BIT ); To insert a new value to the BIT column, use INSERT statement: INSERT INTO table_name (bit_column) VALUES (1);

Can we convert varchar to varbinary in SQL Server?

Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query. The problem is that the query plan hashes are already in binary format, however stored as VARCHAR in the XML Query Plan e.g.

How many bits is a varchar?

The key difference between varchar and nvarchar is the way they are stored, varchar is stored as regular 8-bit data(1 byte per character) and nvarchar stores data at 2 bytes per character.

Can you convert varchar to Nvarchar?

NVARCHAR has higher precedence than the VARCHAR data type. Therefore, during the data type conversion, SQL Server converts the existing VARCHAR values into NVARCHAR.


2 Answers

I suspect that there are other values in addition to 'true' and 'false' in the field 'Flag1'. So check for the values in Flag1.

select distinct Flag1 from YouTable.

Here is my proof:

declare @Flag varchar(25) = 'False'
select CONVERT(Bit, @Flag)

It works fine.

However, this will give the same error.

declare @Flag varchar(25) = '  False' -- Pay attention to the the space in '  False'!
select CONVERT(Bit, @Flag)

-> Msg 245, Level 16, State 1, Line 2 Conversion failed when converting the varchar value ' False' to data type bit.

Pay attention to the the space in ' False' in the error message!

like image 84
Jian Huang Avatar answered Sep 20 '22 20:09

Jian Huang


While selecting from table, you can do this:

SELECT CASE Flag1 WHEN 'true' THEN 1 ELSE 0 END AS FlagVal

Syntax:

CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END 
Searched CASE expression:
CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END
like image 33
Raging Bull Avatar answered Sep 18 '22 20:09

Raging Bull