只有本站会员才能查看附件,请 登录
建表脚本:
create table tb_test(ID int identity(1,1) primary key,AU nvarchar(300))
go
insert into tb_test(AU)
select 'Liu, C; Li, LC; Chen, WQ; Chen, X; Xu, ZH; Bai, SN'
union
select 'Ji, YS; Guo, HW'
union
select 'Cui, WY; Zhao, SF; Polanowska-Grabowska, R; Wang, J; Wei, JX; Dash, B; Chang, SL; Saucerman, JJ; Gu, J; Li, MD'
union
select 'Xiao, A; Wu, YD; Yang, ZP; Hu, YY; Wang, WY; Zhang, YT; Kong, L; Gao, G; Zhu, ZY; Lin, S; Zhang, B'
union
select 'Song, CX; Yi, CQ; He, C'
union
select 'Fan, XX; Zhou, YF; Liu, X; Li, LF; Su, XD'
union
select 'Wen, X; Zhang, CL; Ji, YS; Zhao, Q; He, WR; An, FY; Jiang, LW; Guo, HW'
union
select 'Wang, Q; Fristedt, R; Yu, XH; Chen, ZG; Liu, HT; Lee, Y; Guo, HW; Merchant, SS; Lin, CT'
union
select 'Liang, YH; Gao, R; Su, XD'
union
select 'Zhao, L; Ding, Q; Zeng, J; Wang, FR; Zhang, J; Fan, SJ; He, XQ'
go
从网上找了个函数可以按分号把AU(作者)字段按顺序拆成列:
select *,b.*
from tb_test a
cross apply dbo.Udf_Keywords_Split(a.au) b
如图:
只有本站会员才能查看附件,请 登录
使用函数如下:
CREATE FUNCTION [dbo].[Udf_Keywords_Split]
(
-- Add the parameters for the function here
@KeywordsListString NVARCHAR(MAX)
)
RETURNS
@KeywordsList TABLE
(
-- Add the column definitions for the TABLE variable here
OrderNum int,
Keywords NVARCHAR(MAX)
)
AS
BEGIN
-- Fill the table variable with the rows for your result set
DECLARE @EndFlag INT
DECLARE @KeywordsCount INT
DECLARE @KeywordsListStr NVARCHAR(MAX)
SET @EndFlag=LEN(@KeywordsListString)-LEN(REPLACE(@KeywordsListString,';',''))+1
SET @KeywordsCount=0
SET @KeywordsListStr=ltrim(rtrim(@KeywordsListString))
WHILE @EndFlag>0 AND @KeywordsListStr<>''
BEGIN
IF CHARINDEX(';',@KeywordsListStr)>0
BEGIN
DECLARE @KeywordsStr NVARCHAR(MAX)
SET @KeywordsStr=LEFT(@KeywordsListStr,CHARINDEX(';',@KeywordsListStr)-1)
SET @EndFlag=@EndFlag-1
SET @KeywordsCount=@KeywordsCount+1
SET @KeywordsStr=ltrim(replace(@KeywordsStr,CHAR(10),''))
SET @KeywordsStr=ltrim(replace(@KeywordsStr,CHAR(13),''))
INSERT INTO @KeywordsList(OrderNum,Keywords)
VALUES(@KeywordsCount,@KeywordsStr)
SET @KeywordsListStr=RIGHT(@KeywordsListStr,len(@KeywordsListStr)-CHARINDEX(';',@KeywordsListStr))
END
ELSE
BEGIN
SET @EndFlag=@EndFlag-1
SET @KeywordsCount=@KeywordsCount+1
SET @KeywordsListStr=ltrim(replace(@KeywordsListStr,CHAR(10),''))
SET @KeywordsListStr=ltrim(replace(@KeywordsListStr,CHAR(13),''))
INSERT INTO @KeywordsList(OrderNum,Keywords)
VALUES(@KeywordsCount,ltrim(@KeywordsListStr))
END
END
RETURN
END
怎样写个SQL语句将输出样式如下的数据
ID AU1 AU2 AU3 ........ AU(n)
1 Cui, WY Zhao, SF Polanowska-Grabowska, R NAME(n)
n的最大值可以从dbo.Udf_Keywords_Split(a.au)的OrderNum中查询到,当对应ID没有第x个作者时用NULL填充
我看了PIOVT相关的文章,还是不会,请大神们指教,谢谢