表格来自两个级别的逗号分隔列

时间:2014-03-21 12:27:49

标签: sql sql-server-2008

我有一个旧的数据库,其中有两列包含逗号分隔值,如下所示,

Table Schema with data

SQL FIDDLE LINK for SCHEMA

现在我的问题是我正在尝试将这些值导入到另一个规范化的数据库中。因此,我需要将这些值转换为表格格式,而不是逗号分隔值。

所以我的输出应该是这样的,

enter image description here

2 个答案:

答案 0 :(得分:0)

您需要定义这些列的含义。在你的例子中你丢弃了原始的ID列,在这种情况下,什么是“1,2,3”& “A,B”实际上是什么意思?

我可能会通过对每一行进行游说并使用split函数将每个字段转换为值表来实现此目的。

create FUNCTION dbo.fn_Split1 (@sep nchar(1), @s nvarchar(4000))
RETURNS table
/**************************************************************************************************
 * Author:              http://stackoverflow.com/questions/314824/
 * Description:         splits a string into a table of values, with single-char delimiter.
 * Example Usage:

        select * from dbo.fn_split1(',', '1,2,5,2,,dggsfdsg,456,df,1,2,5,2,,dggsfdsg,456,df,1,2,5,2,,')
 **************************************************************************************************/
AS
RETURN (
    WITH Pieces(pn, start, stop) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      UNION ALL
      SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
      FROM Pieces
      WHERE stop > 0
    )
    SELECT pn,
      SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 4000 END) AS s
    FROM Pieces
  )

答案 1 :(得分:0)

CREATE TABLE #RegionDetail
 (
   Id int identity(1,1) not null,
   RegionId nvarchar(50),
   Zone nvarchar(50) 
 )

INSERT INTO #RegionDetail (RegionId,Zone) values ('1,2,3','A,B')
INSERT INTO #RegionDetail (RegionId,Zone) values ('1,2,3','X,Y')
INSERT INTO #RegionDetail (RegionId,Zone) values ('4,3,5','A,B')

GO

create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))       
returns @temptable TABLE (items varchar(MAX))       
as       
begin      
    declare @idx int       
    declare @slice varchar(8000)       

    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(@Delimiter,@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String       

        if(len(@slice)>0)  
            insert into @temptable(Items) values(@slice)       

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
return 
end;

GO 

SELECT Id,RegionId,Zone FROM #RegionDetail

select 
   r.Id,f.items as RegionId,z.items as Zone
from 
    #RegionDetail r
    cross apply [dbo].[Split](r.RegionId,',') f
    cross apply [dbo].[Split](r.Zone,',') z
order by Id,RegionId,Zone