0

I have the below string which is currently in one column, called Column1, in a table called dbo.faresnumb

Column1
512.65USD/52.65USD/0167025354825

I want to create three new columns from this string called Fare1, Fare2, Number1 like below

Fare1      Fare2      Number1
512.65USD  52.65USD   0167025354825

So the delimter is the / and the character count will not always be the exact same. For example, Fare1 could be 54.00USD rather than 512.65USD and I still need to capture everything before the first /. I know is SAS there is a way to scan a substring to find a delimiter and assign new variables, but I am new to SQL. Any help would be much appreciated!

Thanks, Bennett

1
  • 1
    I think at least you should google it before posting Commented Feb 16, 2018 at 13:06

2 Answers 2

2

Such string operations are a pain in SQL Server. You can do:

select parts.part1 as fare1,
       left(rest, charindex('/', rest) - 1) as fare2,
       stuff(rest, 1, charindex('/', rest), '') as number1
from t cross apply
     (values (left(col, charindex('/', col) - 1),
              stuff(col, 1, charindex('/', col), '')
             )
     ) parts(part1, rest);

Here is a rextester.

Sadly, SQL Server 2016 offers split_string() which makes this simpler. The sad part is that it does not return the position of the substring in the string. That is needed to ensure that the three extracted values are in the right order.

Sign up to request clarification or add additional context in comments.

2 Comments

It surprises me MS haven't added ordinal position yet. The Connect items have had a lot of upvotes, and it would be extremely useful for so many.
Thank you for your suggestion!! I appreciate it!
1

One more way to achieve the same using a bit of XML -

select cast(concat('<x>', REPLACE(Column1, '/', '</x><x>'), '</x>') as xml).value('/x[1]','varchar(100)'), 
       cast(concat('<x>', REPLACE(Column1, '/', '</x><x>'), '</x>') as xml).value('/x[2]','varchar(100)'),
       cast(concat('<x>', REPLACE(Column1, '/', '</x><x>'), '</x>') as xml).value('/x[3]','varchar(100)') from dbo.faresnumb

1 Comment

Thank you for your suggestion!! Much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.