Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using comparison operators in SELECT clause of T-SQL query

How to select a result of comparison operator as a field with type BIT?

How it does work in C#:

bool isGreater = FieldA > FieldB; 

How it doesn't work in T-SQL:

SELECT (FieldA > FieldB) AS BIT FROM t 

How to write such task properly?

like image 485
abatishchev Avatar asked Feb 24 '10 22:02

abatishchev


People also ask

Can you use != In SQL?

There is no != operator according to the ANSI/SQL 92 standard.


2 Answers

You should use CASE clause:

CASE     WHEN FieldA > FieldB THEN 1     ELSE 0 END AS [BIT] 
like image 92
Rockcoder Avatar answered Sep 23 '22 02:09

Rockcoder


Select Convert(Bit, Case When FieldA > FieldB Then 1 Else 0 End) As YourBitColumn 

If you want to return a BIT, then you need the convert (or cast) to a bit data type, otherwise, SQL would interpret the hard coded constant (1 or 0) as an integer.

like image 30
George Mastros Avatar answered Sep 23 '22 02:09

George Mastros