从列中获取id值,然后从另一个表中获取值

时间:2013-07-18 06:12:30

标签: sql sql-server-2008 split

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

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

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

我该怎么做?

1 个答案:

答案 0 :(得分: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 
相关问题