String 1: 1*2*3*4*5*6* String 2: 1*2*3*40*500*6* String 3: 1*2*3*400*5*600* String 4: 1*2*3*4000*50*6000* The goal is to return the following strings: String 1: 4 String 2: 40 String 3: 400 String 4: 4000
答案 0 :(得分:3)
几乎任何解析/拆分功能都可以。这种内联方法不需要UDF,也返回项目序列。
示例强>
Declare @YourTable table (ID int,SomeCol varchar(500))
Insert Into @YourTable values
(1,'1*2*3*4*5*6*'),
(2,'1*2*3*40*500*6*'),
(3,'1*2*3*400*5*600*'),
(4,'1*2*3*4000*50*6000*')
Select A.ID
,B.RetVal
From @YourTable A
Cross Apply (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(A.SomeCol,'*','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
) B
Where RetSeq=4
<强>返回强>
ID RetVal
1 4
2 40
3 400
4 4000
答案 1 :(得分:3)
在SQL Server 2016+中,您可以使用string_split()
。
在2016年之前的SQL Server中,使用Jeff Moden的CSV Splitter表值函数:
select
str
, s.ItemNumber
, s.Item
from t
cross apply dbo.DelimitedSplit8k(t.str,'*') s
where s.ItemNumber = 4
rextester演示:http://rextester.com/HYCF1752
返回:
+---------------------+------------+------+
| str | ItemNumber | Item |
+---------------------+------------+------+
| 1*2*3*4*5*6* | 4 | 4 |
| 1*2*3*40*500*6* | 4 | 40 |
| 1*2*3*400*5*600* | 4 | 400 |
| 1*2*3*4000*50*6000* | 4 | 4000 |
+---------------------+------------+------+
拆分字符串参考: