[英]Extract 1st 2nd 3rd values till nth value from hyphenated string column in SQL Server table
Table has values like 12-43-5765-234-56-24-6456-234-678-9-0-0
with hyphens表具有像12-43-5765-234-56-24-6456-234-678-9-0-0
这样的12-43-5765-234-56-24-6456-234-678-9-0-0
带连字符
I need to take the first value as a separate column and 2nd value as separate column and so on.我需要将第一个值作为单独的列,将第二个值作为单独的列,依此类推。
I tried like this.我是这样试的。
DECLARE @S VARCHAR(MAX);
SET @S = '12-43-5765-234-56-24-6456-234-678-9-0-0'
SELECT SUBSTRING(@S, 0, CHARINDEX('-', @S)) AS first
This above query selects only first value, but how can 4th and fifth value can be extracted from string?上述查询仅选择第一个值,但如何从字符串中提取第 4 个和第 5 个值? like喜欢
12 as first,
43 as second,
5765 as third,
234 as fourth,
56 as fifth,
24 as sixth and so on..
If you have a maximum (or known) number of positions, and DON'T want to go dynamic如果你有一个最大的(或已知的)位置的数目,并且不想去动态
Example例子
DECLARE @S VARCHAR(MAX);
SET @S='12-43-5765-234-56-24-6456-234-678-9-0-0'
Select Pos1 = xDim.value('/x[1]','varchar(max)') --could change to desired datatype (int ?)
,Pos2 = xDim.value('/x[2]','varchar(max)')
,Pos3 = xDim.value('/x[3]','varchar(max)')
,Pos4 = xDim.value('/x[4]','varchar(max)')
,Pos5 = xDim.value('/x[5]','varchar(max)')
,Pos6 = xDim.value('/x[6]','varchar(max)')
,Pos7 = xDim.value('/x[7]','varchar(max)')
,Pos8 = xDim.value('/x[8]','varchar(max)')
,Pos9 = xDim.value('/x[9]','varchar(max)')
,Pos10= xDim.value('/x[10]','varchar(max)')
,Pos11= xDim.value('/x[11]','varchar(max)')
,Pos12= xDim.value('/x[12]','varchar(max)')
,Pos13= xDim.value('/x[13]','varchar(max)')
From (Select Cast('<x>' + replace(@S,'-','</x><x>')+'</x>' as xml) as xDim) as A
Returns退货
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.