逗号分隔值(CSV)到数组

时间:2014-05-29 06:11:38

标签: tsql csv sql-server-2008-r2

declare @inputString nvarchar(20) = 'a,bc,def,ghij'
declare @i int = 1
declare @j int = 0
declare @character nvarchar(1) 
while(@i <= LEN(@inputString))
begin
set @character =  SUBSTRING(@inputstring,@i,1)
if (@character = ',')
begin
substring(@inputstring,@i,1)=' ' --it is showing an error near substring here
end
set @i = @i + 1
end

请帮助我纠正此错误,我们是否可以在表达式的左侧使用substring

我试图获取所有逗号并用空格替换它们。另外,如何将空格分隔值转换为数组?

1 个答案:

答案 0 :(得分:0)

为什么不使用REPLACE替换逗号

declare @inputString nvarchar(20) = 'a,bc,def,ghij';
set @inputString = REPLACE(@inputString, ',', ' ')
select @inputString

您还可以使用以下函数

以表格格式返回空格分隔值
CREATE FUNCTION [dbo].[FnSplit](@text Nvarchar(4000), @delimiter Nvarchar(20))  
RETURNS @Strings TABLE  
(      
   --position int IDENTITY PRIMARY KEY,  
   Splvalue Nvarchar(Max)     
)  
AS  
BEGIN  
DECLARE @index int   
SET @index = -1   
WHILE (LEN(@text) > 0)   
BEGIN    
SET @index = CHARINDEX(@delimiter , @text)    
IF (@index = 0) AND (LEN(@text) > 0)    
  BEGIN     
    INSERT INTO @Strings VALUES (@text)  
      BREAK    
  END    
IF (@index >= 1)    
  BEGIN     
if (@index - 1) = 0  
 INSERT INTO @Strings VALUES (Null)  
else     
 INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))     
SET @text = RIGHT(@text, (LEN(@text) - @index))    
  END    
ELSE   
  SET @text = RIGHT(@text, (LEN(@text) - @index))   
END  
RETURN  
END

并使用它以表格格式获取输出

select * from dbo.FnSplit(@inputString,' ')