I would like to delete parts of an string
.
We have a Table: Locations
mk-MK=New York; sq-AL=Nej York; en-US=New York
mk-MK=London; sq-AL=London; en-US=London
mk-MK=Paris; sq-AL=Paris; en-US=Paris
I Want to remove everything and keep only sq-AL=LocationName
.
I want the result to be:
sq-AL=Nej York;
sq-AL=London;
This is yet another example of the importance of normalized databases.
In a normalized database you would have a table with 2 columns, one for the culture (sq-Al, en-US etc`) and one for the value. I would go a step further and have the cultures in a lookup table.
However, since this is not the case you have to use string manipulations to get the value of a specific culture. you can use SUBSTRING and CHARINDEX to find the specific pattern you want.
This will work in any of the cases represented by the sample data I've listed.
-- Create the table and insert sample data
CREATE TABLE Location ([Name] varchar(100))
INSERT INTO Location ([Name]) VALUES
('en-US=Huston; mk-MK=Huston; sq-AL=Huston;'), -- end of the row, with the ending ';'.
('en-US=New York; mk-MK=New York; sq-AL=Nej York'), -- end of the row, without the ending ';'.
('mk-MK=London; sq-AL=London; en-US=London'), -- middle of the row
('sq-AL=Paris; en-US=Paris; mk-MK=Paris') -- begining of the row
SELECT SUBSTRING(Name,
CHARINDEX('sq-AL=', Name), -- index of 'sq-AL='
CASE WHEN CHARINDEX(';', Name, CHARINDEX('sq-AL=', Name)) > 0 THEN -- If there is a ';' after 'sq-AL='.
CHARINDEX(';', Name, CHARINDEX('sq-AL=', Name)) -- index of the first ';' after 'sq-AL='
- CHARINDEX('sq-AL=', Name) -- index of the first ';' - the index of 'sq-AL=' will give you the length for `Nej York`
ELSE
LEN(Name)
END
) + ';'
FROM Location
-- Cleanup
DROP Table Location
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments