Postgresql

PostgreSQL 中是否有一種簡單的方法來轉義換行符、輸入符和製表符?

  • April 4, 2021

假設我想轉義這些以查看類似的字元串

SELECT *
FROM ( VALUES
 (E'\r\n\t FOO BAR \t\n\r')
) AS t(str);

我如何獲得 c 風格的轉義,\r\n\t FOO BAR \t\n\r退出?

SELECT *
FROM ( VALUES
 (E'foo\nfoo',E'\n\tBAR\t','baz'),
 (E'quz','qaz','quz')
) AS t(x,y,z); 
 x  |        y         |  z  
-----+------------------+-----
foo+|                 +| baz
foo |         BAR      | 
quz | qaz              | quz
(2 rows)

反而想要..

 x       |        y         |  z  
----------+------------------+-----
foo\nfoo | \n\tBAR          | baz
quz      | qaz              | quz
(2 rows)

您可以使用字元串轉義語法和replace(string,substring,replacement)函式,如下所示。

請注意,它在很大程度上取決於standard_conforming_strings設置。應該是on。您可以在此處此處此處找到詳細資訊。

postgres=# \d t
    Table "public.t"
Column | Type | Modifiers 
--------+------+-----------
s      | text | 

postgres=# SELECT s, md5( s ), replace( replace( replace( s, E'\n', '\n' ), E'\t', '\t' ), E'\r', '\r' ) FROM t;
   s     |               md5                |  replace   
----------+----------------------------------+------------
newline:+| 75c093ed14f1239a3510006326a1a260 | newline:\n
         |                                  | 
tab:     | 355393c5cab9aa324c6ec90682b13d7e | tab:\t
cr:\r    | 094911687582e40cfeb6217f8c760543 | cr:\r
(3 rows)

postgresql 沒有這樣做。您正在查看 psql 向您表示的數據。

但是如果您想查看字節,請將數據轉換為字節,然後查看:

jasen=# set bytea_output to escape;
jasen=# SELECT 
    convert_to(x,'utf8') as x_bytes, 
    convert_to(y,'utf8') as y_bytes, 
    convert_to(z,'utf8') as z_bytes
FROM ( VALUES
 (E'foo\nfoo',E'\n\tBAR\t','baz'),
 (E'quz','qaz','quz')
) AS t(x,y,z); 
 x_bytes   |     y_bytes     | z_bytes 
------------+-----------------+---------
foo\012foo | \012\011BAR\011 | baz
quz        | qaz             | quz

引用自:https://dba.stackexchange.com/questions/174513