将sql子查询转换为list或varchar

时间:2010-08-10 08:50:17

标签: sql-server sql-server-2005

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

例如。 如果我有产品表。而且我有产品的外键产品图像表。 现在我想列出所有带有select查询的产品,该查询应该有一个列,其中列出了每个产品的productImage表的pk列表。

我正在使用sql server 2005.我们能以任何方式实现上述目标吗?

3 个答案:

答案 0 :(得分:10)

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为图像列表为null,只需从查询中删除下一行:

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

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

        5 null

答案 1 :(得分:0)

我不确定我是否关注你,但也许你可以尝试添加额外的表格:

表产品 表格图片 表Product_Images。

在最后一个表中,您将至少有3列,Product_Images表的PK,Product_FK和 Images_FK。然后只需

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

您将拥有与产品相关联的图片PK列表

希望这会对你有所帮助, 问候。

答案 2 :(得分:-1)

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

如果您确实需要在数据库上执行此操作,则可以定义标量值函数,您可以为外键提供值,并返回以逗号分隔的列表。你必须在该函数中使用光标才能发挥神奇的效果。