【问题标题】:How to get get Output of SQL query in a flat file using shell script如何使用 shell 脚本在平面文件中获取 SQL 查询的输出
【发布时间】:2015-02-28 17:33:39
【问题描述】:

我想使用 shell 脚本自动化包含多个 SQL 查询的 SQL 文件,同时我想从中获取 last QueryOutput将 SQL 文件转换为任何平面文件。

【问题讨论】:

    标签: sql linux shell unix


    【解决方案1】:

    您可以创建一个文件来执行每个查询,但只发送最后一个查询的输出。

    #!/bin/bash
    
    mysql -h... -u... -p... -e 'query1' > /dev/null
    
    mysql -h... -u... -p... -e 'query2' > /dev/null
    
    mysql -h... -u... -p... -e 'query3' > /result.sql
    

    【讨论】:

      【解决方案2】:

      awk 命令将在文件中查找最后一个以分号分隔的查询并将其通过管道传送到mysql

      awk 'BEGIN {RS=";"} NF > 0 {query=$0; } END {print query}' file.sql | mysql -u username -p password > output.txt
      

      NF > 0 防止将query 设置为最后一个; 之后的空行。

      【讨论】:

      • Sql 查询是多行的,带有“;”在每个查询结束时,像这样
      • 如果我做对了,所有查询都将被执行,而不仅仅是最后一个。
      • select count (*) from custcomps group by 1 having count(*) > 50 ; select count ( unique(Siebel_Ac_No)) from custcomps ; show select * from custcomps ; select * from "EDWPRDE_VW40_OLAP_CMPLNT"."SR_STTS_TYPE_DIM" show select PIH."Party_Idntn_Num" from EDWPRDE_VW40_OLAP_CMPLNT.CMPLNT_DTL CMPS inner join EDWPRDE_VW40_PUB.T01005_Party_IDNTN_HIST PIH on PIH.Party_Id = CMPS."Customer Id" and PIH.Party_Idntn_Type_Id = 2 and PIH.Party_Idntn_End_Dttm = '9999-12-31 23:59:59' where CMPS."As-At Date Id" = current_date and CMPS."Created Date Id" > current_date-365 group by 1;
      • 不,我只想要最后一个查询的输出
      • 我更新了答案以使用awk 来查找基于分号的查询。
      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 2019-09-19
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多