SQL SELECT - 根据条件返回布尔值

时间:2021-07-19 22:51:56

Essentially I'm trying to do this

基本上我正在努力做到这一点

select  u.Hostname, u.IsCustom, (u.Status = 5) as IsActive
from    SiteUrlMappings u

Where 5 is an int representing an "Active" url.

其中5是表示“活动”URL的int。

Of course this doesn't work, and my sql is rusty like an old screwdriver.

当然这不起作用,我的sql就像一把旧螺丝刀一样生锈。

5 个解决方案

#1


24  

You don't need a CASE expression
Just leverage how bit works: all non-zero values give 1 when cast to bit

您不需要CASE表达式只需利用位的工作方式:当转换为位时,所有非零值都为1

SELECT
    u.Hostname,
    u.IsCustom,
    ~ CAST((u.Status - 5) AS bit) AS IsActive
from    SiteUrlMappings u

#2


22  

SQL Server doesn't have a boolean datatype. The closest is bit

SQL Server没有布尔数据类型。最接近的是位

SELECT u.Hostname,
       u.IsCustom,
       CAST(CASE
              WHEN u.Status = 5 THEN 1
              ELSE 0
            END AS BIT) AS IsActive
FROM   SiteUrlMappings u  

#3


5  

You need a case statement, like this:

你需要一个case语句,如下所示:

select  u.Hostname,
        u.IsCustom,
        convert(bit, case when u.Status = 5 then 1 else 0 end) as IsActive

from    SiteUrlMappings u

bit is as close to true boolean as you can get in SQL Server

bit可以在SQL Server中获得,因为它接近于true布尔值

#4


4  

Try this:

尝试这个:

SELECT
    u.Hostname,
    u.IsCustom,
    CASE
WHEN u.Status = 5 THEN
    1
ELSE
    0
END AS IsActive
from    SiteUrlMappings u

#5


0  

You can use CASE ... WHEN syntax instead.

您可以使用CASE ... WHEN语法。

#1


24  

You don't need a CASE expression
Just leverage how bit works: all non-zero values give 1 when cast to bit

您不需要CASE表达式只需利用位的工作方式:当转换为位时,所有非零值都为1

SELECT
    u.Hostname,
    u.IsCustom,
    ~ CAST((u.Status - 5) AS bit) AS IsActive
from    SiteUrlMappings u

#2


22  

SQL Server doesn't have a boolean datatype. The closest is bit

SQL Server没有布尔数据类型。最接近的是位

SELECT u.Hostname,
       u.IsCustom,
       CAST(CASE
              WHEN u.Status = 5 THEN 1
              ELSE 0
            END AS BIT) AS IsActive
FROM   SiteUrlMappings u  

#3


5  

You need a case statement, like this:

你需要一个case语句,如下所示:

select  u.Hostname,
        u.IsCustom,
        convert(bit, case when u.Status = 5 then 1 else 0 end) as IsActive

from    SiteUrlMappings u

bit is as close to true boolean as you can get in SQL Server

bit可以在SQL Server中获得,因为它接近于true布尔值

#4


4  

Try this:

尝试这个:

SELECT
    u.Hostname,
    u.IsCustom,
    CASE
WHEN u.Status = 5 THEN
    1
ELSE
    0
END AS IsActive
from    SiteUrlMappings u

#5


0  

You can use CASE ... WHEN syntax instead.

您可以使用CASE ... WHEN语法。