Cast ‘True’ as Bit

May 7 2008

Okay, I'm a bit slow on the uptake. It took the SQLServerCentral.com question of the day to point this out to me...

Apparently MS made the values "true" and "false" implicitly convertible to BIT (as 1 and 0 respectively) starting with SQL 2005. For many years I've defined variables in stored procedure scripts that emulate the constants TRUE and FALSE... Something like this:

declare @TRUE bit; set @TRUE = 1;
declare @FALSE bit; set @FALSE = 0;

But now, instead, I can just directly reference 'true' or 'false' where necessary, such as in a where clause. For example:

declare @t table (ID int not null, IsFlagged bit not null);
insert @t
      select 1, 0
union select 2, 1
union select 3, 1
;
select count(*) from @t where IsFlagged = 'true';

Or, more plainly:

select cast('true' as bit) as Result;

Of course, this isn't true Boolean type support. And don't get me started on the truly relational equivalents of TRUE and FALSE. But at least it's a step closer. Certainly less typing.

Also note: it does not work to convert directly to INT types though, only the BIT type. Even though BITs are theoretically a sub-type of the general Integer variable class.

MS SQL Server

Comments

Add comment




biuquote
  • Comment
  • Preview
Loading