SQL SP 返回产品映像列表



我想从SQL获取产品图像列表以显示在图像幻灯片中。

但是,我不确定从MS SQL存储过程返回数据的最佳方法。

问题是,使用下面的 SP,我得到了每个图像的重复记录。理想情况下,我想获取一个数组或字符串列表,或者某种从单个记录中分离出数据的方法。但是,我对其他解决方案持开放态度。我的目标是以直观的方式将图像放在页面上。这适用于 ASP.Net C# 应用程序。

这是我的存储过程中的简化选择语句:

  SELECT 
  P.[ProductId]
  ,P.[ProductName]
  ,I.[FileName] as ProductImage
  FROM [Product] P
  LEFT JOIN [ProductImages] I
  on P.ProductId = I.ProductId
  Where P.ProductId = @ProductId

这将返回如下所示的数据:

ProductId         ProductName       ProductImage
1                 Coffee Mug        Mug_Image1.jpg
1                 Coffee Mug        Mug_2.jpg
1                 Coffee Mug        Mug_Img3.jpg

我希望它看起来像这样(但我也想听听其他想法):

ProductId         ProductName       ProductImage
1                 Coffee Mug        Mug_Image1.jpg, Mug_2.jpg, Mug_Img3.jpg

同样,我不确定这是否是最好的方法。

我有两张桌子。一个是产品,另一个是产品图像,它有一个FK到产品表中的ProductId。

最终,我需要构造 JSON 来馈送客户端幻灯片脚本。喜欢这个:

productimages = [
        { "image": "Mug_Image1.jpg", "caption": "", "link": "", "title": "" },
        { "image": "Mug_2.jpg", "caption": "", "link": "", "title": "" },
        { "image": "Mug_Img3.jpg", "caption": "", "link": "", "title": "" }
                                    ];

这是 C#

//Create product object to display on page
ProductEntity product = new ProductEntity();
product.Id = idval;
//Load the product from SP based on ID
ProductWF.LoadProduct(product);
//Render product details on page
ProductNameLabel.Text = product.ProductName;
//Construct JSON image list
StringBuilder sb = new StringBuilder();
etc...

你可以使用这样的东西:

SELECT
   P.[ProductId],
   P.[ProductName],
   FileNames = STUFF(
               (SELECT ', ' + FileName FROM ProductImages 
                WHERE ProductId = P.ProductId FOR XML PATH('')) , 1 , 1 , '')
      FROM 
        [Product] P

以获取每个产品的逗号分隔文件名列表(如果有帮助)。但是,要生成的 JSON 字符串可能会从已有的查询结果中构造起来简单得多。

如果从上面获取查询,则可以将其映射到类:

public class Product
{
   public int ProductId {get; set;}
   public string ProductName {get; set;}
   public string FileNames {get; set;}
}

在服务器端,您必须拆分文件名字符串属性并构造一个 json 字符串。

最新更新