SQL SELECT - Return boolean based on condition

2019-02-05 18:04发布

问题:

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.

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

回答1:

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

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


回答2:

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

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


回答3:

You need a case statement, like this:

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



回答4:

Try this:

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


回答5:

You can use CASE ... WHEN syntax instead.