postgresql 是否可以在 SQL 中将布尔值转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48942233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:41:37  来源:igfitidea点击:

Is it possible to convert a boolean to a string in SQL?

sqlpostgresql

提问by user8659376

I have a column called live_in_citythat provides a boolean value. I want to convert it to a string though.

我有一个名为的列live_in_city,它提供一个布尔值。不过我想将其转换为字符串。

I tried using cast((live_in_city) as varchar(256)), but it says cannot cast type boolean to character varying.

我尝试使用cast((live_in_city) as varchar(256)),但它说不能将类型布尔值转换为字符变化。

Is there another way of doing this?

有没有其他方法可以做到这一点?

采纳答案by Raj

Try using below. Here you can assign value to 1 and 0 . then convert that.

尝试使用下面。在这里,您可以为 1 和 0 赋值。然后转换那个。

Select 
    Cast(Case 
            When live_in_city=1 Then 'True' 
            ELse 'False' END 
        AS Varchar(256))
    from #t 

The above works if live_in_cityis a number (integer, numeric, ...).

如果live_in_city是数字(整数,数字,...),则上述方法有效。

For a real booleancolumn, the following should be used:

对于真正的boolean列,应使用以下内容:

Select Case 
         When live_in_city Then 'True' 
         ELse 'False' 
       END 
from the_table;

回答by clemens

Casting to TEXTworks fine for me in Postgres 9.5:

铸造到TEXT了在Postgres 9.5正常工作对我说:

# select (0 = 0)::TEXT, (0 = 1)::TEXT;
 text | text  
------+-------
 true | false
(1 row)

and also your code works as well:

并且您的代码也能正常工作:

# SELECT cast((1 = 1) as varchar(256)), cast((1 = 0) as varchar(256));
 varchar | varchar 
---------+---------
 true    | false
(1 row)

Note: (1 = 1)and (1 = 0)are placeholders for all possible expressions, that returning trueor false.

注意:(1 = 1)and(1 = 0)是所有可能的表达式的占位符,返回truefalse

回答by Harald Nordgren

You can cast it to text like this:

您可以将其转换为这样的文本:

CAST(table.column AS TEXT)