开发者

Specify data type with column alias in SQL Server 2008

Imagine I have the following SELECT statement in a view (SQL Server 2008):

SELECT (SELECT CASE 
                 WHEN HISTORY.OUTOFSERV = 'Y' OR HISTORY.OUTOFSERV = 'y' THEN 1 
                 ELSE 0 
               END) AS OOS 
  FROM HISTORY

The column OOS ends up being of type int, but I'd like it to be of type b开发者_高级运维it. How can I accomplish this?


Use CAST/CONVERT to explicitly define the data type:

SELECT CAST (CASE 
               WHEN LOWER(h.outofserv) = 'y' THEN 1 
               ELSE 0 
             END AS BIT) AS OOS 
 FROM HISTORY h


you should just use CAST(1 as bit) and CAST(0 as bit) instead of 1 and 0:

SELECT (CASE WHEN HISTORY.OUTOFSERV = 'Y' OR HISTORY.OUTOFSERV = 'y'
             THEN CAST(1 AS bit) 
             ELSE CAST(0 AS bit) 
        END) AS OOS 
FROM HISTORY


Here's a way to get the desired BIT datatype output, and with a little cleaner code using:

  • upper()
  • cast()

    SELECT CAST(CASE
    WHEN UPPER(History.OutofServ) = 'Y' THEN 1
    ELSE 0 END AS BIT) AS OOS FROM History

I hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜