Using comparison operators in SELECT clause of T-SQL query

SqlSql ServerSql Server-2008TsqlComparison Operators

Sql Problem Overview


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?

Sql Solutions


Solution 1 - Sql

You should use CASE clause:

CASE
    WHEN FieldA > FieldB THEN 1
    ELSE 0
END AS [BIT]

Solution 2 - Sql

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.

Solution 3 - Sql

You can use IIF function. For example:

SELECT IIF(FieldA > FieldB, 1, 0) AS YourBitColumn FROM t

IFF Function's syntax like as below:

IIF( boolean_expression, true_value, false_value )

IFF returns, If boolean_expression is true, then true_value, otherwise false_value

For more information about IFF function : Logical Functions - IIF (Transact-SQL)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionabatishchevView Question on Stackoverflow
Solution 1 - SqlRockcoderView Answer on Stackoverflow
Solution 2 - SqlGeorge MastrosView Answer on Stackoverflow
Solution 3 - SqlRamil AliyevView Answer on Stackoverflow