如何在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
如何在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
反斜杠在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客户机中,这两行是否实际为displayed取决于您的SQL客户机.
更新:来自@thedayturns的一个很好的答案,在这里你可以有一个更简单的查询:
E'test line 1\ntest line 2'