Is there a way to get a boolean value without casting in SQL Server?

It seemed very strange to me that simple code like this is invalid:

select * from table where field=true

The alternative apparently being

select * from table where field='true'

Well, I think I can live with it. For one reason or another, I needed to do something similar recently:

select true as somefield,...

The alternative to getting types and all right was much uglier, though:

select cast('true' as bit) as somefield,...

Am I missing something? Is there any built-in way to get true or false value as a boolean without casting?

+7
source share
7 answers

The Sql server does not have a logical data type that you can store in the table, but it does contain a bit of the data type that you can save.

true, , . Sql Server boolean , , TRUE, FALSE UNKNOWN.

.

SELECT *
FROM Table
WHERE Field = 1 --Field = true

, . 1 for true, 0 for false Null for unknown.

+6

- , TSQL. -

select CAST(1 as bit) as somefield
+19

"" "" - , . MSDN .

TRUE FALSE : TRUE 1, FALSE 0.

, .

where ( , ).

select * from table where field='true'

"TRUE" "FALSE" . .

select cast('true' as bit) as somefield,...

MSDN , ( , ) - 0 1.

0 1 . , , .

, , 0 1 int, . 'int', .

select sql_variant_property(0, 'BaseType')
select sql_variant_property(1, 'BaseType')
+6

boolean SQL Server:

DECLARE @myTrue bit = 1;
-- or two lines for old version of SQL Server
-- DECLARE @myTrue bit;
-- SET @myTrue = 1;

SELECT @myTrue AS somefield
+4

1 0, .

select * from table where field=1

select * from table where field=0
+3

, ...

, BIT. , "" - "" ... BIT.

SQL- #, case, :

case when foo = faa then 1 else 0 end as outcome

and when the results were sent to the linq query, the resulting type was changed to INT32. So this failed:

outcome = s.Field<bool>("outcome")

I wanted the result to be allowed for BIT, so I used:

cast(case when foo = faa then 1 else 0 end as bit) as outcome

The point, while TSQL may assume that it is BIT, ADO did not do instead.

All in all, I think I'm saying, don't rely on a framework (.NET or TSQL) to do the dirty work ... If you want BIT, drop it as BIT :)

+1
source
CASE WHEN ISNULL(Attribute1,'0')='1' THEN 'true' Else 'false' End Attribute1
0
source

All Articles