首页 > 代码库 > SQL字段拼接与拆分

SQL字段拼接与拆分

--测试数据:create table #tojoin(    tablename varchar(20) not null,    columnname varchar(20) not null,    primary key clustered(tablename,columnname))gocreate table #tosplit(    tablename varchar(20) not null primary key clustered,    columnnames varchar(max) not null)goinsert 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)goinsert 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 tgroup 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) tcross apply t.columnnamesxml.nodes(/root/columnname) c(columnname)

 

SQL字段拼接与拆分