我的表格中有一列由多个值组成,由-
分隔。
示例:
STB-123456789-010116
我想得到:
col1 col2 col3
STB 123456789 010116
这3个字段将存储在3列的另一个数据库中。
如何获得所需的输出?
答案 0 :(得分:2)
SELECT PARSENAME(REPLACE('STB-123456789-010116','-','.'),3),PARSENAME(REPLACE('STB-123456789-010116','-','.'),2),
PARSENAME(REPLACE('STB-123456789-010116','-','.'),1)
答案 1 :(得分:1)
一种方法是使用内置string functions的Left
,SubString
,Right
,CharIndex
和Reverse
:
DECLARE @S varchar(100) = 'STB-123456789-010116'
SELECT LEFT(@S, CHARINDEX('-', @S) - 1) As LeftSide,
SUBSTRING(@S, CHARINDEX('-', @S) + 1, LEN(@S) - CHARINDEX('-', REVERSE(@S)) - CHARINDEX('-', @S)) As Middle,
RIGHT(@S, CHARINDEX('-', REVERSE(@S)) - 1) As RightSide
LeftSide Middle RightSide
---------------------------------
STB 123456789 010116
答案 2 :(得分:0)
您也可以使用XML:
DECLARE @x xml
;WITH cte AS (
SELECT 1 as id,
'STB-123456789-010116' as some_column
UNION ALL
SELECT 2,
'STB-9876543210-0918677'
)
SELECT @x = (
SELECT CAST('<i id="' + CAST(id as nvarchar(10)) +'"><a>' + REPLACE(some_column,'-','</a><a>') + '</a></i>' as xml)
FROM cte
FOR XML PATH('')
)
SELECT t.v.value('@id','int') as id,
t.v.value('a[1]','nvarchar(100)') as col1,
t.v.value('a[2]','nvarchar(100)') as col2,
t.v.value('a[3]','nvarchar(100)') as col3
FROM @x.nodes('/i') as t(v)
输出:
id col1 col2 col3
1 STB 123456789 010116
2 STB 9876543210 0918677