Search code examples
sqlsql-servervarchar

MSSQL - Remove all text after a '-' in a varchar field


I have a field in one of my tables that has names in it such as:
Category1 - Label1,
Category2 - Label2,
Category3 - Label3 and so on.

I created another field and I want to do an UPDATE that will copy all values over to the new field but so they appear as:
Category1
Category2
Category3

This would mean removing everything from the space before the hyphen to the right.

Note: There will ever only be one hyphen in the string to separate Category from Label.


Solution

  • update your_table
    set col_new = case when charindex('-', col) > 0 
                       then RTRIM(left(col, charindex('-', col) - 1))
                       else col
                  end