显示表中的逗号分隔值

时间:2011-07-11 11:55:23

标签: sql sql-server sql-server-2005

之前我曾就同一架构问过问题。这次我的要求是从表中获取输出。对于架构,请参阅此 question

现在我想从地图表中查询公司ID,并将类别的所有子类别显示为逗号分隔值。情景类似于此。 如果我以公司Id 1登录,我有3个不同的类别。然后在我的网格中,它将显示:

**Category**                                   **Subcategory**

Category1                SubCat1, Subcat2, Subcat3 and so on
Category2                SubCat4, Subcat62, Subcat6 and so on

我的现有查询是:

    SELECT tbl_Category.Name , dbo.fnGetCSValues(@CompanyId) AS Subcategory
      FROM tbl_Company_Category_Map 
  INNER JOIN tbl_Category ON tbl_Company_Category_Map.CategoryId = tbl_Category.Id 
  INNER JOIN tbl_SubCategory ON tbl_Company_Category_Map.SubCategoryId = tbl_SubCategory.Id
     WHERE tbl_Company_Category_Map.CompanyId = @CompanyId
    GROUP BY tbl_Category.Name

使用UDF

ALTER FUNCTION [dbo].[fnGetCSValues] (@Id INT)

RETURNS VARCHAR(8000)
AS
BEGIN

 DECLARE @List VARCHAR(8000)
 SELECT @List =(SELECT tbl_SubCategory.Name    
                FROM      tbl_Company_Category_Map INNER JOIN
                          tbl_Category ON tbl_Company_Category_Map.CategoryId = tbl_Category.Id INNER JOIN
                          tbl_SubCategory ON tbl_Company_Category_Map.SubCategoryId = tbl_SubCategory.Id
                WHERE tbl_Company_Category_Map.CompanyId = @Id
                ORDER by tbl_SubCategory.Name 

                 FOR    XML PATH(''))
 RETURN LEFT(@List,(LEN(@List) -1))
END

1 个答案:

答案 0 :(得分:0)

Declare @Table Table
(
    Category varchar(100),Subcategory varchar(MAX)
)
insert into @Table
Select 'Category1','SubCat1,Subcat2,Subcat3' UNION ALL
Select 'Category2','SubCat4,Subcat62,Subcat6'



--1st option to use master..sptvalue 

Select Category,SUBSTRING(',' + Subcategory + ',', n.Number + 1, CHARINDEX(',', ',' + Subcategory + ',', n.Number + 1) - n.Number - 1) 
From @Table As T
Cross Join master..spt_values As n
WHERE n.Type = 'p'
AND n.Number > 0 
AND n.Number < LEN(',' + Subcategory + ',')
and SUBSTRING(',' + Subcategory + ',', n.Number, 1)=','

--2nd option to use split function
CREATE FUNCTION [dbo].[Split](@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

--call query here
Select Category,items as Subcategory
From @Table As T
Cross Apply dbo.Split(Subcategory,',')