【问题标题】:How to get output of a sql with additional special characters如何获取带有附加特殊字符的 sql 输出
【发布时间】:2019-04-27 20:37:56
【问题描述】:

说来话长……

我正在尝试动态生成交叉表查询并将其作为 psql 脚本运行..

为了实现这一点,我希望生成 sql 的最后一行并将其附加到 sql 的顶部。

sql的最后一行是这样的.... "as final_result(symbol character varying,"431" numeric,"432" numeric,"433" numeric);"

其中,“431”、“432”等是动态生成的,因为它们是枢轴列,它们会不时变化...

所以我写了一个查询来输出文本如下......

psql -c "select distinct '"'||runweek||'" numeric ,' from calendar where runweek between current_runweek()-2 and current_runweek() order by 1;" -U USER -d DBNAME > /tmp/gengen.lst

虽然 sql 提供了输出,但当我将其作为脚本运行时,由于特殊字符('、""、),它会失败。

我应该如何让它工作?然后我的计划是遍历“lst”文件并构建数据透视字符串,并将其附加到 sql 的顶部并执行脚本......(postgres 新手,不知道,动态 sql 生成和执行等。 . 但我对 UNIX 脚本很满意..)

如果我能以某种方式得到输出 (“431”数字,“432”数字......等等),如果有建议来实现这一点,将不胜感激......

【问题讨论】:

  • 如果你从 shell 运行它(并且引用是你的问题),你可以使用 here-document。

标签: postgresql psql


【解决方案1】:

由于您在参数周围使用双引号,因此参数内的双引号必须用反斜杠转义:

psql -c "select distinct '\"'||runweek||'\" numeric ,' from calendar where runweek between current_runweek()-2 and current_runweek() order by 1;"

Heredoc 也可以用来代替-c。它接受多行格式,从而使整个内容更具可读性。

(psql [arguments] <<EOF
  select distinct '"'||runweek||'" numeric ,'
     from calendar 
     where runweek between current_runweek()-2 and current_runweek()
   order by 1;
EOF
) > output

通过使用quote_ident 专门用于从文本值生成带引号的标识符,您甚至不需要添加双引号。查询可能是这样的:

select string_agg( quote_ident(runweek::text), ',' order by runweek)
 from calendar
 where runweek between current_runweek()-2 and current_runweek();

这也解决了您的原始查询在末尾有一个杂散的','而这种形式没有的问题。

【讨论】:

  • 像这样重写它 select string_agg(quote_ident(runweek::text),' numeric,' order by runweek) from (select distinct runweek from calendar where runweek between current_runweek()-2 and current_runweek() ) 一个;将输出作为 ""432" numeric,"433" numeric,"434" 这不是我想要的,但我使用 shell 命令将丢失的“numeric”字符串附加到代码中......同时添加字符串“ numeric , 在子查询中导致整个字符串的“”位置,而不仅仅是“433”或“432”......但至少我有办法继续前进......谢谢......
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2012-05-02
  • 2020-07-13
  • 2011-07-29
  • 1970-01-01
  • 2013-07-07
  • 2021-01-19
相关资源
最近更新 更多