0

Problem: Current input in numeric#; varchar

eg: 404#;a pruchase order

1#; b purchase order

1046#;x y x purchase order from this company

I need to have the numbers at the beginning put in a column and the name of the field after #; in a different column.

Parse will not work because there is a possibility of greater than 4 words in the title

As you can see #; is a common feature in all the inputs.

What I would like to see happen is:

ID           Name
404          a purchase order
1            b purchase order
1046         xyz purchase order from this company 

Any ideas?

I tried How do I split a string so I can access item x?

but that wouldn't work for me

1
  • What version of SQL Server? Commented Aug 21, 2014 at 15:21

3 Answers 3

3
declare @a varchar(20)
set @a = '123#;gunrin gnre'

SELECT 
    SUBSTRING(@a,0,CHARINDEX('#',@a)) AS ID
    , SUBSTRING(@a,CHARINDEX('#',@a)+2,LEN(@a)-CHARINDEX('#',@a)) AS Name
Sign up to request clarification or add additional context in comments.

Comments

1
Declare @Sample NVARCHAR(100)

 SET @Sample = '1046#;x y x purchase order from this company'

SELECT SUBSTRING(@Sample, 1, CHARINDEX('#;', @Sample)-1), SUBSTRING(@Sample, CHARINDEX('#;', @Sample)+2,LEN(@Sample) )

Comments

0

What about:

with Test as (
    select * from (values 
        ('404#;a purchase order'),
        ('1#;b purchase order'),
        ('1046#;xyz purchase order from this company'),
        ('29323982#;evil test 231#;')
    ) tmp(str)        
)
select cast(left(str, idx-1) as int) as ID,
       right(str, len(str)-idx-1)    as Name
from Test t
cross apply (select charindex('#;', t.str) as idx) tmp

-- ID          Name
-- ----------- ------------------------------------------
-- 404         a purchase order
-- 1           b purchase order
-- 1046        xyz purchase order from this company
-- 29323982    evil test 231#;
-- 
-- (4 row(s) affected)

Keep in mind though, that cross apply is MSSQL-specific.

Comments

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.