分割多个字段,然后拼接在一起
SELECT pg.vchcode,pg.ptypeid,pg.ktypeid,pg.dlyorder,pg.pgdetail,pg.IsCut,(CAST(substring(pg.pgQtyStr,b.number,charindex('ǒǜ' ,pg.pgQtyStr +'ǒǜ',b.number)-b.number) AS NUMERIC(22,10))) AS lpgQtyStr, dbo.fn_splitPgCode(pgIDCode,'ǒǜ',len(STUFF('ǒǜ'+ pgQtyStr,b.number+2,LEN(pgQtyStr),''))-len(replace(STUFF('ǒǜ'+ pgQtyStr,b.number+2,LEN(pgQtyStr),''), 'ǒǜ', ' '))-1) lpgIDCode INTO #pg FROM (SELECT * FROM dbo.pgdlyDetail WHERE vchcode = @ovchcode and dlyorder = @nOldDlyOrder ) pg join master..spt_values b on b.type='P' where charindex('ǒǜ','ǒǜ'+pg.pgQtyStr ,b.number)=b.number AND pgQtyStr <>'' AND pgQtyStr <> '-'
效果如下
字符串分割方法
if object_id ('dbo.fn_splitPgCode') is not null drop function dbo.fn_splitPgCode go CREATE FUNCTION fn_splitPgCode( @s varchar(8000), @splitchar VARCHAR(5), @num INT )RETURNS VARCHAR(1000) AS BEGIN Declare @s1 varchar(1000) SET @s1 = '-' SELECT @s1 = col FROM dbo.f_splitSTR(@s,@splitchar) WHERE id = @num RETURN @s1 END go
SET QUOTED_IDENTIFIER ON SET ANSI_NULLS ON GO CREATE FUNCTION f_splitSTR( @s varchar(8000), --待分拆的字符串 @split varchar(10) --数据分隔符 )RETURNS @re TABLE(ID int IDENTITY,col varchar(8000)) AS BEGIN DECLARE @splitlen int SET @splitlen=LEN(@split+'a')-2 WHILE CHARINDEX(@split,@s)>0 BEGIN INSERT @re VALUES(LEFT(@s,CHARINDEX(@split,@s)-1)) SET @s=STUFF(@s,1,CHARINDEX(@split,@s)+@splitlen,'') END INSERT @re VALUES(@s) RETURN END GO
合并
SELECT pgs.PtypeId,pgs.KtypeId,pgs.pgDetail,SUM(pgs.pgDetail) sumqty ,stuff((select 'ǒǜ'+convert(varchar(25), g.pgIDCode) FROM (SELECT pggoodsidcodes.* FROM dbo.pggoodsidcodes WHERE pggoodsidcodes.PtypeId='00009' AND pggoodsidcodes.KtypeId='00002' AND pggoodsidcodes.pgDetail<>0 AND IsUsed=0 AND lockMode='D' ) g WHERE g.PtypeId = pgs.PtypeId AND g.KtypeId=pgs.KtypeId AND g.pgDetail=pgs.pgDetail AND g.goodsorderid=pgs.goodsorderid AND g.IsCut=pgs.IsCut FOR XML PATH('')), 1,2, '') as CustomerName FROM dbo.pggoodsidcodes pgs where pgs.PtypeId='00009' AND pgs.KtypeId='00002' AND IsUsed=0 AND lockMode='D' GROUP BY pgs.PtypeId,pgs.KtypeId,pgs.pgDetail,pgs.goodsorderid,IsCut
效果如下