如何用逗号分隔符将单列值拆分为多列?

时间:2014-02-12 07:51:51

标签: sql-server-2008

请帮帮我。如果有人知道如何用逗号分隔符将单列值拆分到多个列?我已经尝试实现下面给出的查询。我想在此查询中使用内连接,但在执行此查询时它会出现不明确的错误

DECLARE @pivot varchar(8000)
DECLARE @select varchar(8000)

SELECT 
        @pivot=coalesce(@pivot+',','')+'[institute'+cast(number+1 as varchar(10))+']'
FROM 
        master..spt_values where type='p' and 
        number<=(SELECT max(len(instituteid)-len(replace(instituteid,',',''))) FROM PTUAdminPost)

SELECT 
    @select='
        select p.*
        from (
        select 
            id,substring(instituteid, start+2, endPos-Start-2) as token,
            ''institute''+cast(row_number() over(partition by id order by start) as varchar(10)) as n
        from (
            select 
                id, instituteid, n as start, charindex('','',instituteid,n+2) endPos
                from (select number as n from master..spt_values where type=''p'') num
                cross join 
                (
                    select 
                        ap.id, '','' + ap.instituteid +'','' as instituteid 
                    from 
                        PTUAdminPost ap 
                        inner join PTUAdminProperty prp
                        on prp.Id = ap.postapplying
                        where id=2787
                ) m
            where n < len(instituteid)-1
            and substring(instituteid,n+1,1) = '','') as instituteid
        ) pvt
        Pivot ( max(token)for n in ('+@pivot+'))p'
EXEC(@select)

0 个答案:

没有答案