1. 程式人生 > >sql 分隔符字串轉換成表以及多行記錄列值轉換成字串

sql 分隔符字串轉換成表以及多行記錄列值轉換成字串

--1. 字串(分隔符分隔組成的字串)轉換成多行記錄的表
-- Function
create FUNCTION [dbo].[fn_Split1](    
 @String nvarchar (max),    
 @Delimiter nvarchar (10)    
)    
RETURNS @ValueTable TABLE ([Value] NVARCHAR(max),[id] int)    
BEGIN    
 DECLARE @NextString nvarchar(max),    
  @Pos int,    
  @NextPos int,    
  @CommaCheck nvarchar(1),  
 @id int  
  
set @id=1    
     
 SET @NextString = ''    
 SET @CommaCheck = right(@String,1)     
     
 SET  @String = @String + @Delimiter    
     
  SET @Pos = CHARINDEX(@Delimiter,@String)    
  SET @NextPos = 1    
     
 WHILE (@pos <>  0)      
 BEGIN    
  SET @NextString = SUBSTRING(@String,1,@Pos - 1)    
      
  INSERT INTO @ValueTable ( [Value],[id]) VALUES (@NextString,@id)    
      
  SET @String = SUBSTRING(@String,@pos +1,LEN(@String))    
       
  SET @NextPos = @Pos    
  SET @pos  = CHARINDEX(@Delimiter,@String)    
  
 set @id = @id +1  
 END    
     
 RETURN    
END

GO

--使用

SELECT * FROM dbo.fn_Split1('11111;22222;3333;4444',';');   
--結果,列如下
/*
Value	id
----------
11111	1
22222	2
3333	3
4444	4
*/



--2.多行記錄某一個列,轉換成一個字串

IF EXISTS(SELECT TOP 1 1 FROM sysobjects WHERE id=OBJECT_ID('fn_GetProductTypeCodeList') AND type='FN')
DROP FUNCTION  fn_GetProductTypeCodeList
GO
CREATE FUNCTION  fn_GetProductTypeCodeList
( @chvReportProductTypeGUID varchar(40))
RETURNS  varchar(max) 

AS  

BEGIN 

declare @chvProductTypeCodeList varchar(max)
set @chvProductTypeCodeList = ''
select @chvProductTypeCodeList = @chvProductTypeCodeList+';'+ ProductTypeCode from p_Report2ProductType 
WHERE 
[email protected]
set @chvProductTypeCodeList = stuff(@chvProductTypeCodeList,1,1,'') return @chvProductTypeCodeList END GO --使用 SELECT dbo.fn_GetProductTypeCodeList(NEWID()) --結果 /* --多行資料 Value id -------------- 11111 1 22222 2 3333 3 4444 4 --最後得到 11111;22222;3333;4444 */