2012-07-30 164 views
1

我想使用SQL 「拆分」 功能:如何使用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:附近有語法錯誤(' 。 服務器:消息170,15級,狀態1,行 1行:附近有語法錯誤 ''

+0

爲什麼不創建一個sql clr函數?並使用.net框架拆分功能.. – 2012-07-30 12:45:01

回答

0

你必須CSV字符串傳遞給你的分割功能

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

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

現在@result傳遞到您的分割功能

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

試試這個功能

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

    Declare @remainingStr varchar(100)[email protected] 
    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',',') 
0

無論如果eqcode = 'EQL0000004'只返回一個排或一個以上的過濾功能,你可以執行你的[dbo].[Split3]通過使用每個返回行的功能CROSS APPLY

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也適用,如果查詢返回不止一行。