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.
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);
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.
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.
NVARCHAR has higher precedence than the VARCHAR data type. Therefore, during the data type conversion, SQL Server converts the existing VARCHAR values into NVARCHAR.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With