Need to convert gender field has data type as bit.
I used this syntax:
Select case when CAST([GenderIsMale] AS bit)=1 then 'Male'
when CAST([GenderIsMale] AS bit)=0 then 'Female'
else CAST([GenderIsMale] AS bit)
end
Returns the error:
Conversion failed when converting the varchar value 'Male' to data type bit.
Best Answer
The problem is that you have two different return types, depending on the value of
[GenderIsMale]
; the twoWHEN
conditions return a string while theELSE
returns aBIT
. It is easier to see if you format the code nicely:You can test this as follows:
Returns:
You can fix this by returning a string (or literal
NULL
) in theELSE
condition (pick one of thoseELSE
conditions, depending on what you are trying to accomplish):Please note:
Depending on the datatype of the
GenderIsMale
column and the data in it, it is possible that there is an additional source of the error: theCAST
of the value intoBIT
. For example, if the datatype isVARCHAR
, then values of empty string,'true'
,'false'
, and strings of just digits 0 - 9 (no spaces, commas, periods, or minus sign) will convert, but anything else will error. Since you are using SQL Server 2012, you can switch to usingTRY_CAST
(or evenTRY_CONVERT
) to get around that.The commented-out
ELSE
conditions are mainly to show the possible variations for getting the resulting expression to be consistent across all branches of theCASE
statement. But in the scenario here of having aBIT
/ boolean value, if the datatype of theGenderIsMale
column is a number, then the only value that could fall through to theELSE
is aNULL
, hence you would useELSE NULL
. But if the datatype is a string, then you would useELSE [GenderIsMale]
.