Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Function to replace words

Author  Topic 

dnf999
Constraint Violating Yak Guru

253 Posts

Posted - 2013-01-17 : 14:12:56
Hi

Does anybody have function which replaces key words with blank,

i.e. have the following words in a column which I want to replace with ''

Blu R
Dvd
Blu Ray
Dvd/bl
Dvd & Blu
D/b
Dvd Box Se
Dvd & Blu Ray
D/bl
D/

So "Bad boys dvd" would become "Bad Boys"
"Batman D/B" would be come "Batman"

As I have a long list of words, it's quite messy if I use a concatenated replace statement.

Thanks

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-01-17 : 17:37:54
Something to get you started:

Put the keywords into a table and join with that table. See the example below. If you have more than one keyword to be removed in a single sentence, the update statement would need to be run multiple times. Also, it is not quite perfect - if a keyword happens to be the starting or ending portion of a sentence, that gets replaced as well.
CREATE TABLE #keywords(word VARCHAR(32));
INSERT INTO #keywords VALUES
('Blu R'),('Dvd'),('Blu Ray'),('Dvd/bl'),('Dvd & Blu'),('D/b'),('Dvd Box Se'),('Dvd & Blu Ray'),('D/bl'),('D/');

CREATE TABLE #test(sentence VARCHAR(255));
INSERT INTO #test VALUES ('Bad boys dvd'),('Advd'),('xyz');

UPDATE t SET
sentence = COALESCE(REPLACE(REPLACE(t.sentence,' '+word,''),word+' ',''),t.sentence)
FROM
#test t
LEFT JOIN #keywords k ON t.sentence LIKE '%'+k.word+'%'

SELECT * FROM #test;

DROP TABLE #test
DROP TABLE #keywords
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-01-17 : 22:48:33
[code]
UPDATE t SET
sentence = COALESCE(REPLACE(' ' + t.sentence + ' ',' '+ word + ' ',''),t.sentence)
FROM
#test t
LEFT JOIN #keywords k ON ' ' + t.sentence + ' ' LIKE '% '+k.word+' %'
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -