我有一个数据表TableA里面有个字段FieldB,其内容一般如下:
FieldB
AAAA、BBBBBB、CCCCC、EEE
CCCCC、FFF
DDD、KKKKBDC、BBBBBB、MMMDG
GAGAD、AAAA、EEE
NNNN、MMM、FAGFF、CCCCC
。。。
我现在想将字段FieldB按“、”进行分离,然后把值连起来,形成如下的结果:
AAAA、BBBBBB、CCCCC、EEE、FFF、DDD、KKKKBDC、MMMDG、GAGAD、NNNN、MMM、FAGFF
我想在SQL SQLVER中编写一个函数,请问该如何实现?请高手帮忙!
------解决方案--------------------
- SQL code
create table ta(FieldB varchar(20))insert into ta select 'AAAABBBBBB'union all select 'CCCCCEEE'union all select 'CCCCCFFF'union all select 'DDD'union all select 'KKKKBDC' union all select 'BBBBBB' union all select 'MMMDG'union all select 'GAGAD' union all select 'AAAA'union all select 'EEE'union all select 'NNNN' union all select 'MMM' union all select 'FAGFF'union all select 'CCCCC'select * from tacreate function F_FieldB()returns varchar(8000)asbegin declare @str varchar(8000) set @str = '' select @str = @str + ',' + FieldB from ta set @str = right(@str , len(@str) - 1) return(@str)Endselect dbo.F_FieldB()/*AAAABBBBBB,CCCCCEEE,CCCCCFFF,DDD,KKKKBDC,BBBBBB,MMMDG,GAGAD,AAAA,EEE,NNNN,MMM,FAGFF,CCCCC*/
------解决方案--------------------
- SQL code
create table tb(fieldB nvarchar(50))insert into tb select 'AAAA、BBBBBB、CCCCC、EEE'insert into tb select 'CCCCC、FFF'insert into tb select 'DDD、KKKKBDC、BBBBBB、MMMDG'insert into tb select 'GAGAD、AAAA、EEE'insert into tb select 'NNNN、MMM、FAGFF、CCCCC'goselect stuff((select '、'+fieldB from(select distinct fieldB from(select substring(a.fieldB,b.number,charindex('、',a.fieldB+'、',b.number+1)-b.number)fieldB from tb a,master..spt_values bwhere b.type='p' and b.number<=len(a.fieldB) and substring(a.fieldB,b.number,1)<>'、' and substring('、'+a.fieldB,b.number,1)='、')t)t1 for xml path('')),1,1,'')/*AAAA、BBBBBB、CCCCC、DDD、EEE、FAGFF、FFF、GAGAD、KKKKBDC、MMM、MMMDG、NNNN*/godrop table tb