代码之家  ›  专栏  ›  技术社区  ›  Vikas

将SQL子查询转换为list或varchar

  •  1
  • Vikas  · 技术社区  · 15 年前

    我想知道是否可以在varchar数据类型中将子查询结果转换为逗号分隔的列表。

    例如 如果我有产品表。我有产品图片表和产品的外键。 现在,我想列出带有select查询的所有产品,该查询应该有一列,其中包含每个产品的productimage表的pk列表。

    我正在使用SQL Server 2005。我们能以任何方式实现上述目标吗?

    3 回复  |  直到 15 年前
        1
  •  10
  •   Niikola    15 年前
    Select p.ProductID,
           Stuff((Select ','+Cast(ImageID as varchar(10)) 
                    From @ProductImages i 
                   Where p.ProductID=i.ProductId 
                     For XML PATH('')
                 ),1,1,''
                ) as ImageList
      From @Products p
     Where p.ProductID in (Select ProductID From @ProductImages)
    

    以下是我用于此查询的测试数据

    Declare @Products Table (ProductID int primary key, ProductName varchar(20))        
    Declare @ProductImages Table (ProductId int, ImageId int, Primary Key (ProductId, ImageId))
    
    Insert Into @Products 
    Select 1, 'Product1' Union all
    Select 2, 'Product1' Union all
    Select 3, 'Product1' Union all
    Select 4, 'Product1' Union all
    Select 5, 'Product1' 
    
    Insert Into @ProductImages
    Select 1,1 Union all
    Select 1,2 Union all
    Select 1,3 Union all
    Select 2,4 Union all
    Select 2,5 Union all
    Select 3,1 Union all
    Select 4,3 Union all
    Select 4,5 
    

    以下是查询结果:

    ProductID ImageList
    --------- ---------
            1 1,2,3
            2 4,5
            3 1
            4 3,5
    

    如果要使productID 5在图像列表中为空,只需从查询中删除下一行:

    Where p.ProductID in (Select ProductID From @ProductImages)
    

    结果中还有一行(未分配图像):

            5 null
    
        2
  •  0
  •   Sergio Rosas    15 年前

    我不确定是否在跟踪您,但您可以尝试添加一个额外的表:

    表积 表格图像 表产品图片。

    在最后一个表中,您将至少有3列,pk用于product_images表,product_fk和 图像。然后用公正

    SELECT Image_FK FROM Product_Images WHERE Product_Images.Product_FK = ##;
    

    您将拥有与产品关联的图像pk列表

    希望这对你有帮助, 当做。

        3
  •  -1
  •   tdammers    15 年前

    不容易,我发现最好的方法是单独执行子查询,并以编程方式组装逗号分隔的列表。

    如果您确实需要在数据库上执行此操作,那么可以定义一个标量值函数,该函数可以给出外键的值,并返回逗号分隔的列表。不过,您必须在该函数中使用一个光标来实现这种魔力。