How do I remove the first characters from the Rightof a specific column in a table?

Viewed 45

How can I remove things after a characters (-) from the right of a specific column in a table?

Column name is location.

Amsterdam - park - station 7
Rotterdam - van Nellefabriek - straatweg 7
Utrecht - Amsterdamsestraatweg 10

want to see:

Amsterdam - park
Amsterdam - park
Rotterdam - van Nellefabriek 
Utrecht
1 Answers

Please try the following solution.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens VARCHAR(1000));
INSERT INTO @tbl (tokens) VALUES 
('Amsterdam - park - station 7'),
('Rotterdam - van Nellefabriek - straatweg 7'),
('Utrecht - Amsterdamsestraatweg 10'),
('Assen');
-- DDL and sample data population, end

SELECT t.*
    , LEFT(tokens, LEN(tokens) - CHARINDEX('-', REVERSE(tokens))) AS Result
FROM @tbl AS t;

Output

+----+--------------------------------------------+------------------------------+
| ID |                   tokens                   |            Result            |
+----+--------------------------------------------+------------------------------+
|  1 | Amsterdam - park - station 7               | Amsterdam - park             |
|  2 | Rotterdam - van Nellefabriek - straatweg 7 | Rotterdam - van Nellefabriek |
|  3 | Utrecht - Amsterdamsestraatweg 10          | Utrecht                      |
|  4 | Assen                                      | Assen                        |
+----+--------------------------------------------+------------------------------+
Related