【问题标题】:how do I make sure that there is no comma values in my source?如何确保源中没有逗号值?
【发布时间】:2014-01-17 10:56:19
【问题描述】:

我必须将数据提取到逗号分隔的文件 .csv 所以我使用了一个光标和一个看起来像这样的 for 循环:

CURSOR l_body IS
SELECT b.brn_code                            ||','|| 
       t.terminal_no                         ||','||
       t.pos_username                        ||','||
       to_char(t.trn_datetime,'dd-Mon-yyyy') ||','||
       to_char(t.trn_datetime,'hh24:mi:ss')  ||','||
       t.trn_type_code);
FROM tables etc.

我的循环看起来像这样:

FOR x IN l_body LOOP
    utl_file.put_line(out_file_laybye, x.data_line);
    END LOOP;

现在假设我的表中用户名中的值是“John Doe”, 有没有一种方法可以确保在我删除该名称之后的逗号 使用 ||','||? 将其写入文件?

我不想在我的摘录中使用双逗号。 提前致谢。

【问题讨论】:

    标签: sql oracle csv


    【解决方案1】:

    您可以使用replace() 函数删除每个值中的任何逗号:

    select replace(', this, is, a, test,', ',', null) from dual;
    
    REPLACE(',THIS,
    ---------------
     this is a test
    

    你需要为每一列都这样做,所以

    ...
           replace(t.pos_username, ',', null)    ||','||
    ...
    

    你也可以替换一个不同的字符,你也可以使用translate()

    select translate(', this, is, a, test,', ',', ' ') from dual;
    
    TRANSLATE(',THIS,IS,
    --------------------
      this  is  a  test
    

    根据此输出的使用位置,您可能更愿意保留逗号,但以某种方式转义它们。例如,如果您的 CSV 将在 Excel 中使用,您可以将列值括在双引号中,这样值中的逗号就不会与分隔符混淆:

    ...
           '"' || t.pos_username || '"'          ||','||
    ...
    

    这对于逗号可能对输出有帮助的地址之类的东西很有用。当然,您必须确保字符串不包含双引号,或者以某种方式对其进行转义,但可能已经是这样了。

    【讨论】:

    • 非常感谢,Replace() 完全让我忘记了
    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 2020-10-20
    相关资源
    最近更新 更多