Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

sql server - SQL - Split string to columns by multiple delimiters

There appear to be numerous solutions to this problem, however my solutions needs to be dynamic as the number of delimiters changes from between 0 and 3 and needs to be relatively efficient as it will be running across >10m rows across 5 loops.

As example:

  US

  US-AL

  US-AL-Talladega

  US-AL-Talladega-35160

The solution would need to be able to deposit each item in a Country, State, County, ZIP field with a NULL field if the information is not within the string.

Any comments on the best approach would be appreciated or even point me in the direction of where I may have possible missed a solution would be much appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another option is with a little XML in concert with a CROSS or OUTER APPLY

Example

Declare @YourTable table (YourCol varchar(100))
Insert Into @YourTable values
 ('US')
,('US-AL')
,('US-AL-Talladega')
,('US-AL-Talladega-35160')

Select A.* 
      ,B.*
 From @YourTable A
 Outer Apply (
                Select Country = xDim.value('/x[1]','varchar(max)')
                      ,State   = xDim.value('/x[2]','varchar(max)')
                      ,County  = xDim.value('/x[3]','varchar(max)')
                      ,ZIP     = xDim.value('/x[4]','varchar(max)')
                From  (Select Cast('<x>' + replace(YourCol,'-','</x><x>')+'</x>' as xml) as xDim) as A 
             ) B

Returns

YourCol                 Country State   County      ZIP
US                      US      NULL    NULL        NULL
US-AL                   US      AL      NULL        NULL
US-AL-Talladega         US      AL      Talladega   NULL
US-AL-Talladega-35160   US      AL      Talladega   35160

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...