Home > Software engineering >  Replace first word in a string within query
Replace first word in a string within query

Time:09-06

running SQL sever 2016

say i have values like

Type
Coat 2
Furry Coat 1
Coat 2
Furry Coat 3
Coat 5
Furry Coat 1
Coat 3
Furry Coat 3

i want to replace all the strings that say "Coat" to "Skinny Coat" within my query but i dont want to include the "Furry Coat" values. how do i do this? i tried using the

replace(Type, 'Coat', 'Skinny Coat') as Type

but it changes all strings

thanks

CodePudding user response:

You could use CASE logic along with LIKE here:

SELECT Type,
       CASE WHEN Type NOT LIKE 'Furry Coat%'
            THEN REPLACE(Type, 'Coat', 'Skinny Coat') ELSE Type END AS NEW_TYPE
FROM yourTable;

CodePudding user response:

You Exclude 'Furry Coat'

SELECT  REPLACE(Type, 'Coat', 'Skinny Coat') as Type
FROM TABLE
WHERE TYPE NOT IN ('WHAT','YOU','WANT','TO','EXCLUDE);
  • Related