首页 > 代码库 > 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字段拼接与拆分
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。