如何在SQL中使用' - '分隔符从字符串中获取值

时间:2017-11-11 09:10:58

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

我的表格中有一列如下:

Row    Scheme
-----------------------------
001    NULL
002    NULL
003    Scheme1-0.50-Point
003    Scheme1-0.50-Point
004    NULL
005    Scheme1-1.00-Point
006    1_N/A

scheme列的值如下所示:

SchemeName + '-' + Points + '-' + Units 

我希望使用T-SQL输出使用-分隔符

分隔该字符串
Row    Scheme                Name       Point    Unit
------------------------------------------------------
001                  NULL       NULL     NULL    NULL    
002                  NULL       NULL     NULL    NULL    
003    Scheme1-0.50-Point    Scheme1     0.50    Point
003    Scheme1-0.50-Point    Scheme1     0.50    Point
004                  NULL       NULL     NULL    NULL
005    Scheme1-1.00-Point    Scheme1     1.00    Point
006                 1_N/A       NULL     NULL    NULL

1 个答案:

答案 0 :(得分:2)

您可以尝试XML node方法来帮助您:

SELECT DISTINCT 
    [Row], [Scheme],
    a.value ('/A[1]', 'VARCHAR(MAX)') [NAME],
    a.value ('/A[2]', 'VARCHAR(MAX)') [POINT],
    a.value ('/A[3]', 'VARCHAR(MAX)') [UNIT]
FROM 
    (SELECT 
         [Row], [Scheme], 
         CAST('<A>'+REPLACE(ISNULL([Scheme], ''), '-', '</A><A>')+'</A>' AS XML) AS [Scheme1] 
     FROM <table_name>) A 
CROSS APPLY 
    Scheme1.nodes ('/A') as split(a)