简体   繁体   English

如何确保源中没有逗号值?

[英]how do I make sure that there is no comma values in my source?

I have to extract data to a comma delimited file .csv so I'm using a cursor and a for loop that looks like this: 我必须将数据提取到以逗号分隔的文件.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.

and my loop looks like this: 和我的循环看起来像这样:

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

Now say for instance the value in username in my table is 'John Doe,' Is there a way that I can make sure that I remove the comma after that name before I write it to the file using the ||','||? 现在说,例如,表中username的值是“ John Doe”,有没有一种方法可以确保在使用||','||将其写入文件之前,先删除该名称后的逗号。 ?

I don't want to get double commas in my extract. 我不想在摘录中出现两个逗号。 Thanks in advance. 提前致谢。

You can use the replace() function to remove any commas in each value: 您可以使用replace()函数删除每个值中的任何逗号:

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

REPLACE(',THIS,
---------------
 this is a test

You'll need to do it for each column, so 您需要为每一列执行此操作,因此

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

You could also substitute a different character, and you can use translate() for that too: 您也可以替换一个不同的字符,也可以使用translate()

select translate(', this, is, a, test,', ',', ' ') from dual;

TRANSLATE(',THIS,IS,
--------------------
  this  is  a  test

Depending on where this output is going to be used, you might prefer to keep the commas but escape them somehow. 根据将使用此输出的位置,您可能更喜欢保留逗号,但以某种方式将其转义。 If your CSV will be used in Excel, for example, you can wrap the column value in double-quotes so the commas within a value are not confused with separators: 例如,如果您的CSV将在Excel中使用,则可以将列值用双引号引起来,以使值中的逗号不会与分隔符混淆:

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

That's useful for something like an address where the commas might be helpful in the output. 这对于地址之类的内容很有用,其中逗号可能会对输出有所帮助。 Of course, you have to make sure the string doesn't contain double-quotes, or escape those somehow, but that was probably already the case. 当然,您必须确保该字符串不包含双引号,或者以某种方式对其进行转义,但是事实可能已经如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM