简体   繁体   English

如何在没有if / case流的情况下在SQL中返回是或否

[英]How to return Yes or No in SQL without if/case flows

Apart from the IFs and the CASEs from SQL, is there another way to return a table of "Yes"/"No" (in SQL)? 除了SQL的IF和CASE外,还有另一种方法可以返回“是” /“否”表(在SQL中)吗?

EDIT: Yes, it's bad practice, and no I can't do so in the application (it's a school project with specific requirements) 编辑:是的,这是一个不好的做法,不,我不能在应用程序中这样做(这是一个有特定要求的学校项目)

The following is bad practice: 以下是不良做法:

You can have a column that has the string values "Yes" and "No" and then just select from that column. 您可以有一列,其字符串值为“ Yes”和“ No”,然后从该列中进行选择。

You will then have to maintain this columns values. 然后,您将必须维护此列的值。

A better practice would be: 更好的做法是:

Have a bit column and then in the selects against that column have a case statement to return string values. 有一个bit列,然后在针对该列的select中有一个case语句返回字符串值。

use an inline view to translate 0 to 'No' and and 1 to 'Yes' , though you could just stop at no. 使用内联视图将0转换为'No' ,将1转换为'Yes' ,尽管您可以停在no。

SELECT yesNo.Option
FROM YourTable A
LEFT JOIN (SELECT 1 ID, 'YES' as Option UNION ALL SELECT 0, 'No') YesNo
 on A.Field1 = yesNo.ID

This assumes that 0 is in the results of mytable somewhere. 假定mytable的结果中的某个位置为0。

  1. Field1 should be the the column name having 0 or 1 or whatever in it you need to translate Field1应该是具有0或1或您需要翻译的任何内容的列名
  2. yourTable should be just that the table in question (or query) yourTable应该只是所讨论的表(或查询)
  3. All this does is create an inline view with a list of hard coded translations. 所有这些操作就是创建一个内嵌视图,其中包含一系列硬编码的翻译。 Better would be to have a translation table and simply use it. 最好有一个转换表并简单地使用它。

A good idea would be the use of UNION between two selects, one with 'yes' and one with 'no'. 一个好主意是在两个选择之间使用UNION,一个选择为“是”,另一个选择为“否”。 But the above answers are enough. 但是以上答案就足够了。 Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM