1

我希望使用 SQL“拆分”功能:

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'),';')

错误

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

4

3 回答 3

0

您必须将 CSV 字符串传递给您的拆分函数

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

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

现在将@result 传递给您的拆分函数

Select * from dbo.Split3(@result,';')
于 2012-07-30T12:25:33.763 回答
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 的答案):

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

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

不同之处在于,CROSS APPLY如果查询返回多行,这也有效。

于 2012-07-30T17:12:40.090 回答
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',',')
于 2012-07-30T14:30:04.423 回答