Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server replace, remove all after certain character

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 ";"

like image 763
Jimmy Avatar asked Nov 03 '09 15:11

Jimmy


People also ask

How do I remove a specific part of a string in SQL?

We can remove part of the string using REPLACE() function. We can use this function if we know the exact character of the string to remove. REMOVE(): This function replaces all occurrences of a substring within a new substring.

How do I get all the items left of a character in SQL?

SQL Server LEFT() function overview The LEFT() function extracts a given number of characters from the left side of a supplied string. For example, LEFT('SQL Server', 3) returns SQL . In this syntax: The input_string can be a literal string, variable, or column.

How can I replace part of a string in SQL?

SQL Server REPLACE() FunctionThe REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive.


2 Answers

Use LEFT combined with CHARINDEX:

UPDATE MyTable SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1) WHERE CHARINDEX(';', MyText) > 0 

Note that the WHERE clause skips updating rows in which there is no semicolon.

Here is some code to verify the SQL above works:

declare @MyTable table ([id] int primary key clustered, MyText varchar(100)) insert into @MyTable ([id], MyText) select 1, 'some text; some more text' union all select 2, 'text again; even more text' union all select 3, 'text without a semicolon' union all select 4, null -- test NULLs union all select 5, '' -- test empty string union all select 6, 'test 3 semicolons; second part; third part;' union all select 7, ';' -- test semicolon by itself      UPDATE @MyTable SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1) WHERE CHARINDEX(';', MyText) > 0  select * from @MyTable 

I get the following results:

id MyText -- ------------------------- 1  some text 2  text again 3  text without a semicolon 4  NULL 5        (empty string) 6  test 3 semicolons 7        (empty string) 
like image 119
Paul Williams Avatar answered Oct 13 '22 19:10

Paul Williams


For the times when some fields have a ";" and some do not you can also add a semi-colon to the field and use the same method described.

SET MyText = LEFT(MyText+';', CHARINDEX(';',MyText+';')-1) 
like image 25
Rashlien Avatar answered Oct 13 '22 18:10

Rashlien