question

David 2 1 avatar image
David 2 1 asked

How To Output Data In CSV Format If Fields Have NULLs?

I know this can be done using DTS however I would like to know how I can output data in csv format using a query if the columns contain nulls?

For example, if you create and insert into the following table then try to output to a comma seperated string the values get truncated:

create table testcol(
col001 varchar(10),
col002 varchar(10),
col003 varchar(10))

insert into testcol values('A','B','C')
insert into testcol values('A','B',NULL)
insert into testcol values('A',NULL,'C')
insert into testcol values(NULL,'B','C')
insert into testcol values('A',NULL,NULL)

select col001 +','+ col002 +',' col003
from testcol

col003


A,B,
A,B,
NULL
NULL
NULL

Thanks as always.

t-sqlsql-server-2000
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

graz avatar image
graz answered

You can use COALESCE to replace NULLs with another value. So something like this should work:

select COALESCE(col001, '') +','+ COALESCE(col002,'') +',' + COALESCE(col003, '') from testcol

This replaces the NULLs with an empty string.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

TG avatar image
TG answered

You can use BCP to output CSVs. This link has the BCP reference as well as examples: http://msdn.microsoft.com/en-us/library/ms162802.aspx

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.