标签:
--测试数据: 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)
标签:
原文地址:http://www.cnblogs.com/streetpasser/p/5820816.html