Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've found it very weird that simple code like this is not valid:

select * from table where field=true

The alternative apparently being

select * from table where field='true'

Ok, guess I can live with that. For one reason or another I needed to do something like this recently:

select true as somefield,...

The alternative to get types and everything right was much more ugly though:

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

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

like image 376
Earlz Avatar asked Jun 22 '10 17:06

Earlz


People also ask

What can be used instead of CAST in SQL?

Both CAST and CONVERT are functions used to convert one data type to another data type. It is mainly used in the Microsoft SQL program, and both are often used interchangeably.

How do you give a Boolean value in SQL?

You can insert a boolean value using the INSERT statement: INSERT INTO testbool (sometext, is_checked) VALUES ('a', TRUE); INSERT INTO testbool (sometext, is_checked) VALUES ('b', FALSE); When you select a boolean value, it is displayed as either 't' or 'f'.

How do you create a boolean field in SQL Server?

In SQL you use 0 and 1 to set a bit field (just as a yes/no field in Access). In Management Studio it displays as a false/true value (at least in recent versions). When accessing the database through ASP.NET it will expose the field as a boolean value.

Is there a boolean data type in SQL Server?

There is boolean data type in SQL Server. Its values can be TRUE , FALSE or UNKNOWN . However, the boolean data type is only the result of a boolean expression containing some combination of comparison operators (e.g. = , <> , < , >= ) or logical operators (e.g. AND , OR , IN , EXISTS ).


1 Answers

Bits are the datatype most commonly used to represent a boolean in T-SQL. I typically do something like this:

select CAST(1 as bit) as somefield
like image 183
Andy_Vulhop Avatar answered Oct 25 '22 03:10

Andy_Vulhop