码迷,mamicode.com
首页 > 数据库 > 详细

SQL字段拼接与拆分

时间:2016-08-30 10:39:04      阅读:500      评论:0      收藏:0      [点我收藏+]

标签:

--测试数据:
create table #tojoin(
    tablename varchar(20) not null,
    columnname varchar(20) not null,
    primary key clustered(tablename,columnname))
go
create table #tosplit(
    tablename varchar(20) not null primary key clustered,
    columnnames varchar(max) not null)
go
insert into #tojoin values(tblemployee,employeecode)
insert into #tojoin values(tblemployee,employeename)
insert into #tojoin values(tblemployee,hiredate)
insert into #tojoin values(tblemployee,jobcode)
insert into #tojoin values(tblemployee,reporttocode)
insert into #tojoin values(tbljob,jobcode)
insert into #tojoin values(tbljob,jobtitle)
insert into #tojoin values(tbljob,joblevel)
insert into #tojoin values(tbljob,departmentcode)
insert into #tojoin values(tbldepartment,departmentcode)
insert into #tojoin values(tbldepartment,departmentname)
go
insert into #tosplit values(tbldepartment,departmentcode,departmentname)
insert into #tosplit values(tblemployee,employeecode,employeename,hiredate,jobcode,reporttocode)
insert into #tosplit values(tbljob,departmentcode,jobcode,joblevel,jobtitle)
go
--拼接(join),sql server 2005的for xml扩展可以将一个列表转成一个字串:
select
    t.tablename,
    columnnames = stuff(
        (select , + c.columnname
        from #tojoin c
        where c.tablename = t.tablename
        for xml path(‘‘)),
        1,1,‘‘)
from #tojoin t
group by t.tablename
--切分(split),使用sql server 2005对xquery的支持:
select
    t.tablename,
    columnname = c.columnname.value(.,varchar(20))
from (
    select
        tablename,
        columnnamesxml = cast(<root> + replace((select columnname = columnnames for xml path(‘‘)),,,</columnname><columnname>) + </root> as xml)
    from #tosplit
) t
cross apply t.columnnamesxml.nodes(/root/columnname) c(columnname)

 

SQL字段拼接与拆分

标签:

原文地址:http://www.cnblogs.com/streetpasser/p/5820816.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!