SQL字段拼接与拆分

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL字段拼接与拆分相关的知识,希望对你有一定的参考价值。

--测试数据:
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字段拼接与拆分的主要内容,如果未能解决你的问题,请参考以下文章

SQL server拆分字段的SQL语句

java--sql模糊查询(字符串拆分与拼接)

java--sql模糊查询(字符串拆分与拼接)

oracle sql 字符串拆分的查询的问题,急!!!

字段是多个值拼接的,怎么一一取出来

sql将字符串拆分为始终相同数量的片段