在 T-SQL 查询的 SELECT 子句中使用比较运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2330324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using comparison operators in SELECT clause of T-SQL query
提问by abatishchev
How to select a result of comparison operator as a field with type BIT?
如何选择比较运算符的结果作为 BIT 类型的字段?
How it does work in C#
:
它是如何工作的C#
:
bool isGreater = FieldA > FieldB;
How it doesn't work in T-SQL
:
它如何不起作用T-SQL
:
SELECT (FieldA > FieldB) AS BIT FROM t
How to write such task properly?
如何正确编写这样的任务?
回答by Rockcoder
You should use CASE clause:
您应该使用 CASE 子句:
CASE
WHEN FieldA > FieldB THEN 1
ELSE 0
END AS [BIT]
回答by George Mastros
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.
如果要返回 BIT,则需要将转换(或强制转换)为位数据类型,否则 SQL 会将硬编码常量(1 或 0)解释为整数。