Omtara
Omtara

Reputation: 3001

T-SQL Select Equality Result

In the following snippet, I am getting an error in line #4 (Incorrect Syntax near '='). I need to have an equality result displayed as a column in a select statement.

declare @five int
set @five = 5

declare @bool bit
set @bool = (@five = 6)

select @five, @bool

The result set should have two columns: 5 false

Upvotes: 1

Views: 762

Answers (4)

Yuriy Galanter
Yuriy Galanter

Reputation: 39777

As an exotic approach - if you don't want to use CASE logic - bitwise operands work too:

declare @five int
set @five = 5

declare @bool bit
set @bool = (@five ^ 5)

select @five, ~@bool

Upvotes: 1

dknaack
dknaack

Reputation: 60516

You can do this using CASE

declare @five int
set @five = 5

select @five, CASE WHEN @five = 6 THEN 1 ELSE 0 END

Upvotes: 1

Taryn
Taryn

Reputation: 247840

You need a CASE statement around that logic:

declare @five int
set @five = 5

declare @bool bit
set @bool = CASE WHEN @five = 6 THEN 1 ELSE 0 END

select @five, @bool

Upvotes: 2

usr
usr

Reputation: 171206

T-SQL does not have a real boolean type. It is a weird situation. Here is the solution:

set @bool = case when @five = 6 then 1 else 0 end

Truth expressions, which would be of boolean type in other languages, don't have a type in T-SQL. You can only use truth expressions in special syntactic places like where, if and case.

Upvotes: 5

Related Questions