tags:

views:

1737

answers:

4

Hi,

I have a table with the columns employee, address, city, state and zipcode. I have merged address, city, state, zipcode to a single column 'address' separating each field by comma.

My issue is, if one of the fields is null, an extra comma will be inserted. For example if city is null the resulting value will be like address,,state,zipcode. I need to remove this extra comma. How to do this? Please help.

+9  A: 

You could use a case when construct

   ... = case when city is null then '' else city + ',' end

If the values are already in the database you could replace it this way:

   UPDATE tableX SET address= replace(address, ',,', ',')

Execute it N times to be sure to cover even the "all fields are null" case.

splattne
I'm pretty sure REPLACE() always replaces all occurrences. At least, it does in tSQL and MySQL, I'm not sure if it's part of the vanilla SQL standard.
Adam Bellaire
Yes, but select for example select replace(',,,', ',,', ',') results in ,,
splattne
+1  A: 

or you can do this manually in php

<?php

$str = 'address,,state,zipcode';

$str = preg_replace('/,{2,}/i', ',', $str);
echo $str;

?>

I believe you can do this in your language too

Irmantas
A: 

Use replace when you concat your string for insert :

REPLACE('address,,state,zipcode', ',,' , ',' )
Bigballs
A: 

What about REPLACE('address,,,,,,state,,,,,,,,zipcode', ',,' , ',' )

I need 'address,state,zipcode' as answer.