Reputation: 95
I apologize if this has already been done but I'm having trouble finding an answer.
I'm trying to clean up some data after rebuilding a database. The database is for an art store. The old way of doing it is we'd have a Product table and the Product Name said the name of the art and then "by so and so"
So for example one product might have the name "Mona Lisa by Leonardo Da Vinci"
Recently we wanted to add functionality to the website to be able to index products by artists. So I created an artist table with it's own name field and I no longer want the Artist Name in the Product Name.
So I want to remove everything from the "by" onward.
So instead of "Mona Lisa by Leonardo Da Vinci" just "Mona Lisa"
How can I do this?
Upvotes: 2
Views: 3146
Reputation: 1730
If using TSQL:
DECLARE @v varchar(150)
SET @v = 'Mona Lisa By Lenoardo Da Vinci'
--Work
SELECT RTrim(LEFT(@v, CHARINDEX('By',@v)-1)) AS Work
--Other Examples of CHARINDEX()+LEN()+RIGHT/LEFT()
--Creator
SELECT LTrim(RIGHT(@v, LEN(@v)-CHARINDEX('By',@v)-1)) AS Creator
--Both
SELECT RTrim(LEFT(@v, CHARINDEX('By',@v)-1)) AS Work,
LTrim(RIGHT(@v, LEN(@v)-CHARINDEX('By',@v)-1)) AS Creator
Upvotes: 0
Reputation: 17451
If you're sure every product record has " by " followed by the artist name, you can:
Upvotes: 1
Reputation: 2617
Here's the code you need:
UPDATE Product
SET ProductName = LEFT(ProductName, LEN(ProductName) - CHARINDEX(' yb ', REVERSE(ProductName)) -3 );
This approach ensures that you slice off the text beginning at the last instance of the word " by " surrounded by spaces. Otherwise, "Lady by the Lake by Joe Jones" would become "Lady", and "Abby Road by The Beatles" would become "Ab".
The call to REVERSE flips the order of the characters around so you can search backwards. The call to CHARINDEX finds the first instance of " yb " in this reversed string, which happens to be the last instance of " by " in the original string. Then truncate to that point. Voila.
Good luck!
Upvotes: 4