将组合列值分解为不同的行

时间:2017-04-13 08:41:39

标签: sql sql-server tsql split

我有一个药房表,其中包含PharmacyID和Regimen,如下所示;

PharmacyID  Regimen 
140646      3TC/D4T/EFV
140653      ABC/D4T/NVP

我的愿望就是得到这样的东西;

PharmacyID  Regimen 
140646      3TC
140646      D4T
140646      EFV
140653      ABC
140653      D4T
140653      NVP

我坚持使用谷歌搜索我没有尝试任何解决方案

3 个答案:

答案 0 :(得分:1)

这可以通过XML实现 on-the-fly 字符串拆分方法:

DECLARE @tbl TABLE(PharmacyID INT,Regimen VARCHAR(100)); 
INSERT INTO @tbl VALUES(140646,'3TC/D4T/EFV')
                      ,(140653,'ABC/D4T/NVP');

WITH Casted AS (
                SELECT PharmacyID
                      ,CAST('<x>' + REPLACE((SELECT Regimen AS [*] FOR XML PATH('')),'/','</x><x>') + '</x>' AS XML) AS TheXML
                FROM @tbl
               )
SELECT PharmacyID 
      ,a.x.value(N'(./text())[1]','nvarchar(max)') AS Regimen
FROM Casted
CROSS APPLY Casted.TheXML.nodes(N'/x') AS A(x)

答案 1 :(得分:0)

create function [dbo].[udf_splitstring] (@tokens    varchar(max),
                                   @delimiter varchar(5))
returns @split table (
  token varchar(200) not null )
as



  begin

      declare @list xml

      select @list = cast('<a>'
                          + replace(@tokens, @delimiter, '</a><a>')
                          + '</a>' as xml)

      insert into @split
                  (token)
      select ltrim(t.value('.', 'varchar(200)')) as data
      from   @list.nodes('/a') as x(t)

      return

  end  



    CREATE TABLE #Table111
        ([PharmacyID] int, [Regimen] varchar(11))
    ;

    INSERT INTO #Table111
        ([PharmacyID], [Regimen])
    VALUES
        (140646, '3TC/D4T/EFV'),
        (140653, 'ABC/D4T/NVP')
    ;
    select [PharmacyID], token FROM #Table111 as t1
    CROSS APPLY [dbo].UDF_SPLITSTRING([Regimen],'/') as t2

输出

PharmacyID  token
140646  3TC
140646  D4T
140646  EFV
140653  ABC
140653  D4T
140653  NVP

答案 2 :(得分:0)

create table #temp1(string1 varchar(max))
Insert into #temp1 
Values('3TC/D4T/EFV'),('ABC/D4T/NVP')

    SELECT 
   Replace(Replace(CAST( Tbl.Col.query('.') as varchar(max)),'<a>',''),'</a>','')
    FROM 
(Select cast('<a>'+ replace(string1, '/', '</a><a>') + '</a>' as xml)as t 
  from #temp1) tl
Cross apply 
    tl.t.nodes('/a') AS Tbl(Col)