STUFF function in SQL Server and in ORACLE

4.4k views Asked by At

I have two STUFF questions for this topic.

First question is STUFF function in SQL Server. 2nd question is about the STUFF function in Oracle (8i).

Question 1: How can I remove the , from the column I want to stuff?

Example, given table:

ID      Country     Payment     Product
12345       USA     Cash        Red wine
12345       USA     Cash    
12345       USA     Cash

Using this script, it produces:

select distinct Country, Payment,
stuff(isnull((select ', ' + x.Product from #temp x where x.ID = t.ID
group by x.Product for xml path ('')), ''), 1, 2, '') as Product


ID      Country     Payment     Product
12345   USA         Cash       , Red wine

How can I remove result to show just Red wine only (remove the comma (,)?

PLEASE NOTE: I did not write this STUFF function. It is written by someone named OMG Ponies.

Question 2: Same as question 1 but the syntax is in Oracle:

select distinct ID, Country, Payment, WM_CONCAT(Product) AS Products
from
(
select distinct ID, Country, Payment, Product
from temp table
)x
group by ID, Country, Payment

I would like my result to show just Red wine only (remove the comma (,).

1

There are 1 answers

1
Taryn On BEST ANSWER

Question 1: As far as the SQL Server part of the answer it looks like you have empty strings in your Product field - they are not nulls if there is not one. So you can use the following. I added the line and (product != '' and product is not null) to your Stuff() part and it will remove the extra comma:

select distinct Country, Payment,
    stuff(isnull((select ', ' + x.Product 
                    from test x 
                    where x.ID = t.ID 
                      and (product != '' and product is not null)
                    group by x.Product for xml path ('')), ''), 1, 2, '') as Product
from test t

See SQL Fiddle with Demo

Question 2: I do not have access to an Oracle 8i version but I am going to guess that if you exclude the values with the empty string the comma will disappear.