How to convert a varchar column to bit column in SQL SERVER
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!
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