似乎有很多解决方案,但是我的解决方案必须动态,因为定界符的数量在0到3之间变化,并且必须相对有效,因为它将在5个循环中跨> 10m行运行。
例如:
US
US-AL
US-AL-Talladega
US-AL-Talladega-35160
如果信息不在字符串中,则解决方案将需要能够将每个项目存放在具有NULL字段的Country,State,County,ZIP字段中。
对于最好的方法的任何评论将不胜感激,甚至指出我可能会错过解决方案的方向
答案 0 :(得分:2)
另一种选择是与CROSS或OUTER APPLY配合使用一些XML
示例
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
返回
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
答案 1 :(得分:0)
您将需要定界分隔符。就像来自http://www.sqlservercentral.com/articles/Tally+Table/72993/的DelimitedSplit8K
; with tbl as
(
select col = 'US' union all
select col = 'US-AL' union all
select col = 'US-AL-Talladega' union all
select col = 'US-AL-Talladega-35160'
)
select t.col,
max(case when ItemNumber = 1 then Item end) as Country,
max(case when ItemNumber = 2 then Item end) as State,
max(case when ItemNumber = 3 then Item end) as County,
max(case when ItemNumber = 4 then Item end) as Zip
from tbl t
cross apply dbo.[DelimitedSplit8K](t.col, '-')
group by t.col