12

I'm writing a SQL query in SQL Server in which I need to replace multiple string values with a single string value. For example

Product     Quantity
-------     --------
Apple       2
Orange      3
Banana      1
Vegetable   7
Dairy       6

would become

Product     Quantity
-------     --------
Fruit       2
Fruit       3
Fruit       1
Vegetable   7
Dairy       6

The only way I know how to do this is to use a nested REPLACE in the SELECT clause.

SELECT
  REPLACE('Banana', REPLACE('Orange', REPLACE('Banana', Product, 'Fruit'),
           'Fruit'), 'Fruit') AS Product
FROM
  Table

Is there an easier way?

EDIT: There may be other values in the Product category. See edited example above.

7 Answers 7

20

BradC has the best answer so far, but in case you are for some reason unable to create the additional table I wanted to post an adaption of Kibbee's answer:

SELECT
    CASE WHEN Product IN ('Banana', 'Apple', 'Orange') Then 'Fruit'
    ELSE Product END 
FROM [Table]
Sign up to request clarification or add additional context in comments.

2 Comments

This will work the best for my purposes since the database I'm pulling from is an archive. Otherwise adding a category column would be the way to go. Thanks!
He's talking adding a little lookup table, and that's pretty easy to do, even for an archive db.
11

Make a new "category" table that has a list of your products, along with the "category" to which they belong.

Then just do an inner join.

1 Comment

This would be a good solution except that I'm pulling from a read-only archive.
7
Select
Case Product WHEN 'Banana' Then 'Fruit'
WHEN 'Apple' Then 'Fruit'
WHEN 'Orange' Then 'Fruit'
ELSE Product
END
FROM Table

Comments

1

If there are no other products than those mentioned you could do:

SELECT 'Fruit' AS Product,
        Quantity
FROM Table

If there are other products jus add a WHERE clause

WHERE Product IN ('Banana', 'Orange', 'Apple')

Comments

1

You could create a temp table with a single column 'Product' column, and insert all the product names you want to replace.

Then do an inner join against the target table for your update.

UPDATE
    Table
SET Product = 'Fruit'
FROM
    Table t1 INNER JOIN #Table t2 on t1.Product = t2.Product

Comments

0

The suggestion to create a "category" table is going to be your best choice for the long run.

For examples check out this link: Data belongs in your tables - not in your code

Comments

0

Single quotes to delimit text in SQL:

CASE WHEN ShiptoPlant IN (';','/',' ') Then '' ELSE ShipToPlant END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.