Monday, February 13, 2006

Use CHARINDEX, LEN and SUBSTRING To Find Data Between Characters

Let's say you get data in the following format aaaa/bbbb/cccc/dddd/eeee
What you need from this file is just the data between the first and the last forward slash (in thid case bbbb)
If there is no slash in the file then grab all the data, if there is only 1 slash then grab everything after that slash
This was actually one of the questions that I have answered on tek-tips so yes data like this does exist.
How do you attack such a problem?
First you have to find the first slash, you do that by using CHARINDEX, CHARINDEX will return the position where the first slash is located, then you use CHARINDEX again with SUBSTRING to find the Second slash, finally you use SUBSTRING with the LEFT function and the difference between the 2 CHARINDEX calls as the length
I used a replace function at the beginning to check if there is more than 1 slash or not and then a case statement later on depending on the outcome of that replace function
Let’s see how I did it

--Create some test data
CREATE TABLE #test (ValueField VARCHAR(50))
SELECT ' /yyyy/bbbb ' UNION ALL
SELECT 'zzzzz/c/defgh ' UNION ALL

--This is our delimiter
DECLARE @Delimiter CHAR(1)
SET @Delimiter = '/'

--Show the whole field and the extracted value
SELECT ValueField AS Originalvalue,
CASE WHEN LEN(ValueField) -LEN(REPLACE(ValueField,@Delimiter,'')) > 1
THEN LEFT(SUBSTRING(ValueField,CHARINDEX(@Delimiter,ValueField)+1 ,LEN(ValueField)),CHARINDEX(@Delimiter,SUBSTRING(ValueField,CHARINDEX(@Delimiter,ValueField)+1 ,LEN(ValueField)))-1)
ELSE SUBSTRING(ValueField,CHARINDEX(@Delimiter,ValueField)+1 ,LEN(ValueField))END AS ExtractedValue
FROM #test

No comments: