SQL Server INLINE IF ELSE [英] SQL Server INLINE IF ELSE

查看:175
本文介绍了SQL Server INLINE IF ELSE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的表中,我得到一个列,其值为0或1.如果该列为0,则将值输出为no;如果1我应该为所有行输出'是'。如何仅使用SQL语句执行此操作。谢谢

In my table I got a column whose value is whether 0 or 1. If that column is 0 I output the value as 'no'; if 1 I should output as 'yes' for all rows. How can I do this only using SQL statement. Thanks

推荐答案

SQL Server没有内联 if 语句,但是它有一个内嵌的 case 可以用来完成同样的事情。

SQL Server does not have an inline if statement, but it does have an inline case that can be use to accomplish the same.

Case有两种形式,一种是:

Case has two forms, one is:

select 
 case MyFlag 
   when 1 then 'YES'
   when 0 then 'NO'
   else 'OOPS'
 end
from MyTable

它的使用就像C语言中的切换和其他语言一样是:

where it's used just like a switch in C-like languages and the other is:

select 
 case 
   when MyFlag = 1 then 'YES'
   when MyFlag = 0 then 'NO'
   -- when some unrelated condition...
   else 'OOPS'
 end
from MyTable

它会有条件地评估条件列表并返回第一个条件。

where it senquentially evaluates a list of conditions and returns the first that is fulfiled.

PS 结束部分是强制性的,我通常会忘记这一点。
通常情况下,一个简单的案例可以完全内联,例如

P.S. The end part is mandatory, and I usually forget that. It's also usual for a simple case stament to be completely inlined, like

select (case MyFlag when 1 then 'Yes' else 'No' end) as MyFlagDesc

这篇关于SQL Server INLINE IF ELSE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆