分号分隔到sql server中其他列的值

时间:2016-03-30 08:03:13

标签: sql sql-server sql-server-2008 tsql

我有一个表格,其列的值由半冒号分隔。 关注的是列中的值是不固定的。它从1开始,最后达到80分号。  我试图将每个单独的值放在单独的列

SQL SERVER 2008代码

DECLARE @Table TABLE(
        Val VARCHAR(50)
)

INSERT INTO @Table (Val) SELECT '2Xcalcium; kidney' union all SELECT     '3XMagnessium; liver' union all SELECT '2-ECG;3XSODIUM;DIALYSIS'

SELECT  *,
        CAST(LEFT(Val,CHARINDEX(';',Val)-1) AS VARCHAR) FirstValue,
        CAST(RIGHT(Val,LEN(Val) - CHARINDEX(';',Val)) AS VARCHAR) SecondValue
FROM    @Table

我尝试了上面的代码,但这仅限于2个分号。请分享您的专业知识。

3 个答案:

答案 0 :(得分:1)

提供的大多数链接将元素提取到行中 如果您更喜欢使用现有逻辑并将单个元素提取到单独的列中,则可以使用多个级联的CROSS APPLY。

SELECT  t.Val,
    v1.V as V1, 
    v2.V as V2,
    v3.V as V3
FROM    @Table t
    cross apply
    (
        select  V   = LEFT(t.Val, CHARINDEX(';', t.Val + ';') - 1),
            Val = STUFF(t.Val, 1, CHARINDEX(';', t.Val + ';'), '')

    ) v1
    cross apply
    (
        select  V   = LEFT(v1.Val, CHARINDEX(';', v1.Val + ';') - 1),
            Val = STUFF(v1.Val, 1, CHARINDEX(';', v1.Val + ';'), '')

    ) v2
    cross apply
    (
        select  V   = LEFT(v2.Val, CHARINDEX(';', v2.Val + ';') - 1),
            Val = STUFF(v2.Val, 1, CHARINDEX(';', v2.Val + ';'), '')

    ) v3

答案 1 :(得分:1)

试试这样:

DECLARE @Table TABLE(
        Val VARCHAR(50)
)

INSERT INTO @Table (Val) SELECT '2Xcalcium; kidney' union all SELECT     '3XMagnessium; liver' union all SELECT '2-ECG;3XSODIUM;DIALYSIS';

;WITH Splitted AS
(
    SELECT *
          ,CAST('<x>' + REPLACE(Val,';','</x><x>') + '</x>' AS XML)  ValuesAsXML
    FROM @Table
)
SELECT  *
       ,ValuesAsXML.value('x[1]','varchar(max)') AS FirstCol
       ,ValuesAsXML.value('x[2]','varchar(max)') AS SecondCol
       ,ValuesAsXML.value('x[3]','varchar(max)') AS ThirdCol
       ,ValuesAsXML.value('x[4]','varchar(max)') AS FourthCol
       ,ValuesAsXML.value('x[5]','varchar(max)') AS FifthCol
FROM    Splitted

结果

Val                     FirstCol     SecondCol  ThirdCol    FourthCol   FifthCol
2Xcalcium; kidney       2Xcalcium    kidney     NULL        NULL        NULL
3XMagnessium; liver     3XMagnessium liver      NULL        NULL        NULL
2-ECG;3XSODIUM;DIALYSIS 2-ECG        3XSODIUM   DIALYSIS    NULL        NULL

答案 2 :(得分:0)

根据您的问题,您似乎拥有以下格式的数据。这可以通过numbers表轻松完成..

declare @string varchar(max)
set @string='s,t,a,c,k'



select substring(','+@string+',',n+1,charindex(',',','+@string+',',n+1)-n-1)
from 
numbers 
where n<=len(@string)
and substring(','+@string+',',n,1)=','

<强>输出:

s
t
a
c
k

少数宝石:
https://dba.stackexchange.com/questions/11506/why-are-numbers-tables-invaluable http://sqlperformance.com/2012/07/t-sql-queries/split-strings