简体   繁体   English

当数据包含逗号时,将sql转换为CSV

[英]Spooling sql to a CSV when data contains commas

I'm trying to spool a sql query to a CSV file using a command prompt, however one column of data I'm returning contains comma's in the data and is causing the data to go into the next column. 我正在尝试使用命令提示符将sql查询假脱机到CSV文件,但是我返回的一列数据在数据中包含逗号并导致数据进入下一列。 Is there a way to get around this? 有办法解决这个问题吗? Ideally, I would like this particular column returned in the middle of query, not at the end. 理想情况下,我希望在查询过程中返回此特定列,而不是最后。

I'm currently using the following commands: 我目前正在使用以下命令:

set termout off;
set colsep ',';
set underline off;
set feedback off;
set pagesize 0;
set linesize 1500;
set trimspool on;

I know the set colsep ',' command is the issue however, haven't been able to figure out what to replace it with. 我知道set colsep','命令是问题,然而,无法弄清楚要替换它的内容。 Does anyone have any recommendations? 有没有人有任何建议?

Also, right before my sql query, I'm using a select statement to pull the header information. 此外,在我的SQL查询之前,我正在使用select语句来提取标头信息。 Select 'a, b, c' from dual; 从双重中选择“a,b,c”; Not sure if that makes a difference in the answer or not. 不确定这是否会对答案产生影响。

Two potential answers. 两个可能的答案。 Neither of them perfect. 它们都不完美。 If you have commas in some of the results, but no pipes ( | ), you could switch to a pipe-delimited with 如果在某些结果中有逗号但没有管道( | ),则可以切换到以管道分隔的

set colsep '|'

Most software that can read csv will do just fine with that format. 大多数可以读取csv软件都可以使用该格式。

If that doesn't work for you, you can realize that to treat commas within a column, you'll need to wrap every data item in quotes: 如果这对您不起作用,您可以意识到要处理列中的逗号,您需要将每个数据项包装在引号中:

"data 1","data 2","data,with,commas"

To do this, each separator will need to be "," so you can 要做到这一点,每个分隔符都需要","所以你可以

set colsep '","'

This will not have quotation marks at the beginning and ending of each line, so you can then wrap every line in quotes with sed : 这在每行的开头和结尾都没有引号,所以你可以用sed用引号括起每一行:

sed 's/^[^$]*$/"&"/' 

You can modify your select query like 您可以修改您的选择查询

select REPLACE(column_name, ',',' ') column name from table_name

This will replace comma value from your column data with space. 这将用空格替换列数据中的逗号值。

You can modify your query that returns the result set by surrounding that column with double-quotes. 您可以通过用双引号括起该列来修改返回结果集的查询。 Assuming b is the culprit: 假设b是罪魁祸首:

select a
      , '"' || trim(B) || '"' as b
      , c
from your_table;

Proper syntax depends on your RDBMS version of course. 正确的语法取决于您的RDBMS版本。

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

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