具有位置ID的拆分字符串

时间:2013-06-17 19:31:50

标签: string split sql-server-2012-express

我目前正在对数据挖掘进行一些研究,我的研究数据表看起来如下

ID   Author  
1    Ali,Ahmad,David,Kumar
2    Aslam,Abid,John

现在我想将逗号分隔的作者名称拆分为多个行与position_ID 例如

ID         Author         Position_ID  
1          Ali                 1
1          Ahmad               2
1          David               3
1          Kumar               4
2          Aslam               1
2          Shahzad             2
2          John                3

我目前已经创建了一个split函数和以下查询,它只能将作者列值拆分为多行,但无法将字符串中的作者position_ID转换为单独的列。请给我一些建议。![在此处输入图片说明] [1] 提前致谢

CREATE Function [dbo].[SplitString]
(@List Varchar(Max), @Delimiter Char(1))
Returns @Items 
Table (Item Varchar(max))
As
Begin
Declare @Item Varchar(max), @Pos TinyInt
While Len(@List) > 0 
Begin
Set @Pos = CharIndex(@Delimiter, @List)
If @Pos = 0 Set @Pos = Len(@List) + 1 
Set @Item = Left(@List, @Pos - 1)
Insert @Items 
Select Ltrim(Rtrim(@Item))
Set @List = SubString(@List, @Pos + Len(@Delimiter), Len(@List))
End
Return
End

declare @TAB table (strg varchar(max),Research_ID bigint)
insert @TAB
select authors,Research_ID from Citation
Select S.item As [Authors],Research_ID
From @TAB T
Cross apply [dbo].[SplitString](T.strg,',') S;

1 个答案:

答案 0 :(得分:1)

请试试这个

  

CREATE函数[dbo]。[listtorow2](@ l varchar(200),@ id int)       返回@csv表(strdata varchar(20),id INT,Position_ID int)       如       开始

  declare @xml xml
  set @xml = '<root><record>' + replace(@l,',','</record><record>') +
 '</record></root>'

  insert into @csv(strdata,id,Position_ID)

select *,@id,ROW_NUMBER()OVER(ORDER BY (SELECT 1)) from(
select  t.value('.','varchar(150)') as [items]
from @xml.nodes('//root/record') as a(t)) data

  return
end

go

DECLARE @t TABLE(id INT,autor VARCHAR(50))
INSERT INTO @t(id,autor)values (1,'Ali,Ahmad,David,Kumar'),(2,'Aslam,Abid,John')


SELECT t.id,strdata,Position_ID
FROM @t t 
CROSS APPLY[dbo].[listtorow2](t.autor,id) t1