2011-01-10 84 views
1

我有一个如下所示的数据集(输入)。SQL Server 2008从记录字段中拆分字符串

IR# CR# 
1  1,2 
2  3 
3  4,5,6 

我想下面的输出。这个例子你可以考虑所有的字段varchar。

IR# CR# 
1  1 
1  2 
2  3 
3  4 
3  5 
3  6 

我的UDF到CSV字符串分割成行......但不是在一个表中拆分1行成多行,然后联盟将下一行等

谢谢!

回答

1

结合使用CROSS APPLY拆分UDF。我用于我的示例的字符串拆分器来自here

/* Create function for purposes of demo */ 
CREATE FUNCTION [dbo].[fnParseStringTSQL] (@string NVARCHAR(MAX),@separator NCHAR(1)) 
RETURNS @parsedString TABLE (string NVARCHAR(MAX)) 
AS 
BEGIN 
    DECLARE @position int 
    SET @position = 1 
    SET @string = @string + @separator 
    WHILE charindex(@separator,@string,@position) <> 0 
     BEGIN 
     INSERT into @parsedString 
     SELECT substring(@string, @position, charindex(@separator,@string,@position) - @position) 
     SET @position = charindex(@separator,@string,@position) + 1 
     END 
    RETURN 
END 
go 

/* Set up sample data */ 
declare @t table (
    IR int, 
    CR varchar(100) 
) 

insert into @t 
    (IR, CR) 
    select 1, '1,2' union all 
    select 2, '3' union all 
    select 3, '4,5,6' 

/* Here's the query that solves the problem */ 
select t.IR, p.string 
    from @t t 
     cross apply [dbo].[fnParseStringTSQL](t.CR,',') p 


/* clean up after demo */ 
drop function [dbo].[fnParseStringTSQL] 
+0

真棒。谢谢。我需要看看交叉申请更多! – thomas 2011-01-10 17:26:12