【问题标题】:PostgreSQL newline characterPostgreSQL 换行符
【发布时间】:2016-07-01 22:23:59
【问题描述】:

如何在PostgreSQL中使用newline character

这是我实验中的错误脚本:

select 'test line 1'||'\n'||'test line 2';

我希望sql editor 显示我上面脚本的结果:

test line 1
test line 2

但不幸的是,当我在 sql 编辑器中运行脚本时,我只是从脚本中得到了这个结果:

test line 1 test line 2

【问题讨论】:

  • @Elad,我的问题是关于“选择”查询。读取表中的数据没有插入“创建”。 a_horse_with_no_name 的答案现在足以解决我的问题。
  • You are missing e right before new line literal 的答案与这里给出的答案相同。
  • 你在这部分的意思是“'||'\n'||'”,在我的代码中?

标签: string postgresql newline


【解决方案1】:

反斜杠在SQL中没有特殊含义,所以'\n'是一个反斜杠后跟字符n

要在字符串文字中使用“转义序列”,您需要使用"extended" constant

select 'test line 1'||E'\n'||'test line 2';

另一种选择是使用chr() 函数:

select 'test line 1'||chr(10)||'test line 2';

或者干脆把换行符放在字符串常量中:

select 'test line 1
test line 2';

这实际上是否在您的 SQL 客户端中显示为两行,取决于您的 SQL 客户端。


更新:@thedayturns 提供了一个很好的答案,您可以在其中进行更简单的查询:

E'test line 1\ntest line 2'

【讨论】:

  • 只扩展字符串的换行符部分有点傻吧?你可以做E'test line 1\ntest line 2'
  • @thedayturns 谢谢。我成功地使用您的答案来查询包含序列化数据的列(具体的 YAML 字符串,如 { my_data: [ { data_type: 'MyType', data_id: 113 } ] })。例如select * from table_name where column_name = E'---\n:my_data:\n- :data_type: MyType\n :data_id: 113\n'
  • E'test line 1\ntest line 2' 中前面的E 是做什么的?这最终成为了我的解决方案。
猜你喜欢
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 2013-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多