views:

1920

answers:

3

My data looks like

ID    MyText
1     some text; some more text
2     text again; even more text

How can I update MyText to drop everything after the semi-colon and including the semi colon, so I'm left with the following:

ID    MyText
1     some text
2     text again

I've looked at SQL Server Replace, but can't think of a viable way of checking for the ";"

+1  A: 

Use CHARINDEX to find the ";". Then use SUBSTRING to just return the part before the ";".

David
+1  A: 
UPDATE MyTable
   SET MyText = SUBSTRING(MyText, 1, CHARINDEX(';', MyText) - 1)
 WHERE CHARINDEX(';', MyText) > 0
najmeddine
Just tried this, it seems to leave the ; at the end. ;)
James.Elsey
fixed, thanks .
najmeddine
+3  A: 

Use LEFT combined with CHARINDEX:

update MyTable set MyText = left(MyText, charindex(';', MyText) - 1)

Paul Williams
Thanks this works great! ;)
James.Elsey
What if MyText does not contain the ';' character? In that case, wouldn't you be using a negative 1 as the second parameter in left(). In that case, on my box, I get an error of "Invalid length parameter passed to the substring function."
Mike