1

我有一个用逗号分隔的列值

GoalTag:All Tags,TaskTag:All Tags,GoalId:All,TaskId:All,MaxGoal:5,MaxTask:5

如您所见,我有 6 个用逗号分隔的值,所以当我拆分时,第一个值将是

 GoalTag:All Tags

我如何通过调用表值函数来做到这一点(获取由逗号分隔的值)

Select * from dbo.CustomSplit((SELECT FilterNames FROM TblUserFilterView where UserId = 325 AND Entity = 'Dashboard'),',')

的定义dbo.CustomSplit看起来像

ALTER FUNCTION [dbo].[CustomSplit](@String varchar(8000), @Delimiter char(1))     
returns @temptable TABLE (Items varchar(8000))     
as     
begin     
    declare @idx int     
    declare @slice varchar(8000)     

    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

现在我需要做的是,我需要在":"ie“所有标签”之后获取值,它可能是一些其他记录的一些 id,假设它可能是“142”。我需要得到这个Id,然后从表中得到对应的值。

我怎样才能做到这一点?

4

1 回答 1

1

尝试这个:

SELECT Substring(s.items, 1 + Charindex ( ':', s.items), 
       Len(s.items) - Charindex (':', 
       s.items)) 
FROM   (SELECT * 
       FROM   dbo.Customsplit((SELECT filternames 
                            FROM   tbluserfilterview 
                            WHERE  userid = 325 
                                   AND entity = 'Dashboard'), ',')) AS s 

您可以创建另一个函数:

CREATE FUNCTION [dbo].[Customsplit2](@string    VARCHAR(8000), 
                                    @Delimiter CHAR(1)) 
returns VARCHAR(4000) 
AS 
  BEGIN 
      DECLARE @result NVARCHAR(4000) 
      SELECT @result = Substring(@string, 1 + Charindex ( @Delimiter, @string), 
                                        Len(@string) - Charindex (@Delimiter, 
                                                       @string) 
                       ) 
      RETURN @result 
  END 

并像这样使用它:

SELECT [dbo].Customsplit2(s.items, ':') AS Tag 
FROM   (SELECT * 
        FROM   dbo.Customsplit((SELECT filternames 
                                FROM   tbluserfilterview 
                                WHERE  userid = 325 
                                       AND entity = 'Dashboard'), ',')) AS s 
于 2013-07-18T06:39:33.090 回答