简体   繁体   中英

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

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? 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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM