如何使用SQL SPLIT函数?

时间:2012-07-30 12:10:36

标签: sql-server

我希望使用SQL“split”函数:

alter FUNCTION [dbo].[Split3] (@String nvarchar(1000), @Delimiter char(1))     
returns @temptable TABLE (items nvarchar(1000))       
as       
begin       
   declare @idx int       
    declare @slice nvarchar(1000)       

    select @idx = 1       
        if len(@String)<1 or @String is null  return       

   while @idx!= 0       
   begin       
       set @idx = charindex(@Delimiter,@String)       
       if @idx!=0       
           set @slice = left(@String,@idx - 1)       
       else       
          set @slice = @String       

       if(len(@slice)>0)  
           insert into @temptable(Items) values(@slice)       

       set @String = right(@String,len(@String) - @idx)       
       if len(@String) = 0 break       
   end   
return       
end


Select * from dbo.Split3 ((Select eqipproc from equipmast where eqcode = 'EQL0000004'),';')
  

ERROR

     

服务器:消息170,级别15,状态1,行1   第1行:'('附近的语法不正确。   服务器:消息170,级别15,状态1,行1   第1行:','附近的语法不正确。

3 个答案:

答案 0 :(得分:0)

您必须将CSV字符串传递给拆分功能

DECLARE @result nvarchar(max)
SET @result = ''

SELECT @result = @result + [eqipproc ] + N';'
equipmast where eqcode = 'EQL0000004'

现在将@result传递给你的分割函数

Select * from dbo.Split3(@result,';')

答案 1 :(得分:0)

尝试此功能

 CREATE Function dbo.Str_Split(@string varchar(100),@dl varchar(2))
    Returns @outputtbl Table(col varchar(5))
    As
    BEGIN

    Declare @remainingStr varchar(100)=@string
    if(CHARINDEX(@dl,@remainingStr,1) = 0)
    begin
    INSERT INTO @outputtbl
    select @remainingStr
    end
    else
    begin
    While(CHARINDEX(@dl,@remainingStr,1) > 0)
    BEGIN
    INSERT INTO @outputtbl
    select LEFT(@remainingStr,CHARINDEX(@dl,@remainingStr,1)-1)
    SET @remainingStr=RIGHT(@remainingStr,LEN(@remainingStr)-CHARINDEX(@dl,@remainingStr,1))
    end
    INSERT INTO @outputtbl
    select @remainingStr
    END

    Return
    END
        --select * from dbo.Str_Split('ab,cd,efg',',')

答案 2 :(得分:0)

无论按eqcode = 'EQL0000004'过滤只返回一行还是多行,您都可以使用CROSS APPLY为每个返回的行执行[dbo].[Split3]函数:

select s.*
from equipmast as e
cross apply dbo.Split3(e.eqipproc , ';') as s
where e.eqcode = 'EQL0000004'

注意:上面的CROSS APPLY解决方案与以下解决方案相同(类似于Utkarsh's answer):

declare @s nvarchar(1000)
select @s = eqipproc from equipmast where eqcode = 'EQL0000004'

select * from dbo.Split3(@s, '.')

不同之处在于,如果查询返回多行,CROSS APPLY也可以。