要求 :1.回车空格消除。
2.进展情况相同的要去重
3.方括号内容要消除
4.按 年、月、任务编码 合并成一条数据
--创建该函数 nsc_StrSplit 传一个值 并按‘]’分隔成多条记录 存到一个表里 CREATE FUNCTION [dbo].[nsc_StrSplit] ( @str VARCHAR(4000) ) RETURNS @tableName TABLE ( str2table VARCHAR(4000) ) AS BEGIN --SET @str = @str + ',' DECLARE @insertStr VARCHAR(4000) --截取后的第一个字符串 DECLARE @newstr VARCHAR(4000) --截取第一个字符串后剩余的字符串 SET @insertStr = LEFT(@str, CHARINDEX(']', @str) - 1) SET @newstr = STUFF(@str, 1, CHARINDEX(']', @str), '') INSERT @tableName VALUES ( @insertStr ) WHILE ( LEN(@newstr) > 0 ) BEGIN SET @insertStr = LEFT(@newstr, CHARINDEX(']', @newstr) - 1) INSERT @tableName VALUES ( @insertStr ) SET @newstr = STUFF(@newstr, 1, CHARINDEX(']', @newstr), '') END RETURN END GO
create table #jzztmx( id int identity(1,1), iyear numeric(20, 0), imonth numeric(20, 0), rwbm nvarchar(500), ggjzqk nvarchar(4000) ) insert into #jzztmx --2.将【】内容删除 再去重 select distinct iyear,imonth,rwbm,substring(mss,0,CHARINDEX('[',mss) ) ggjzqk from ( --1.将进展状态里按】分割成多条数据存到一个表里 并消除回车换行, SELECT iyear,imonth,rwbm,replace(replace(str2table,CHAR(13),''),CHAR(10),'') mss FROM (select iyear,gjyf imonth,rwbm,jzqk from NSC_A8_shijigenjin where (sfsc !='删除' or sfsc is null) and iyear = @iyear and gjyf <=@imonth ) a OUTER APPLY nsc_StrSplit(a.jzqk) ) a order by rwbm --按年月任务编码 合成一条记录 select iyear,imonth,rwbm, jzqk=( (select ltrim(ggjzqk) +'' from #jzztmx where iyear=a.iyear and imonth=a.imonth and rwbm =a.rwbm for xml path('')) ) into #jzztzx from #jzztmx a group by iyear,imonth,rwbm
结果: