如何通过sqlserver以单独的逗号在一个变量中返回图像名称 [英] How to return image name in one variable in separated comma by sqlserver

查看:88
本文介绍了如何通过sqlserver以单独的逗号在一个变量中返回图像名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  ALTER   FUNCTION  [dbo]。[ return_imagename_productid_Product ] 

@ id int

RETURNS varchar 200
AS
BEGIN
声明 @ imagename as varchar 200
set @imagename =(选择 ImageName 来自 dbo.tbl_ProductImage where ProductId = @ id

返回 @ imagename
END





以上这个函数可以通过productid返回一个以上的图像名。

ImageName

aa.jpg

bb.jpg

cc.jpg



但我的存储超过了价值图像名称在一个变量中以逗号分隔。

ImageName

aa.jpg,bb.jpg,cc.jpg







以上功能之后调用storeprocedure





  alter   proc  [dbo]。[fetch_withImageName_Product] 
as
选择 distinct pro .ID,pro.ProductName,pro.ProductCode,pro.ProductCost,
选择 dbo.return_imagename_productid _Product (pro.ID)) as ImageName,
proBrand.BrandId,( select b.Name 来自 dbo.Brand b 其中 b.Id = proBrand.BrandId) as BrandNameName
来自 dbo.tbl_Products pro
加入 dbo.tbl_Product_Brand proBrand pro.ID = proBrand.ProductId



请帮助我。 ....



[edit]已添加代码块[/ edit]

解决方案

要将所有值都返回到逗号分隔的字符串中,您可以使用COALESCE的魔力()



  DECLARE   @ images   NVARCHAR ( MAX)

SELECT @ images = COALESCE @ images + < span class =code-string>' ,'' )+ image_name
FROM images_table


< blockquote>

  SELECT 东西(( SELECT  ' ,' + ImageName  From  dbo.tbl_ProductImage 其中​​ ProductId =  @ id   FOR  XML PATH(' )), 1  1 ' ' as 图像


ALTER FUNCTION [dbo].[return_imagename_productid_Product]
(
    @id int
)
RETURNS varchar(200)
AS
BEGIN
    declare @imagename as varchar(200)
    set @imagename =( select ImageName from dbo.tbl_ProductImage where ProductId = @id)

    return @imagename
END



above this function to return imagename by productid more than one.
ImageName
aa.jpg
bb.jpg
cc.jpg

But I am store more than value image name in one variable in separated comma.
ImageName
aa.jpg, bb.jpg, cc.jpg



After that above function to call in storeprocedure


alter proc [dbo].[fetch_withImageName_Product]
as
select distinct pro.ID,pro.ProductName, pro.ProductCode,pro.ProductCost,
(select dbo.return_imagename_productid_Product(pro.ID))as ImageName,
proBrand.BrandId, (select b.Name from dbo.Brand b where b.Id= proBrand.BrandId)as BrandNameName
 from dbo.tbl_Products pro
join dbo.tbl_Product_Brand proBrand on pro.ID = proBrand.ProductId


please help me.....

[edit]Code block added[/edit]

解决方案

To return all values into a comma separated string you can use the magic of COALESCE()

DECLARE @images NVARCHAR (MAX)

SELECT @images = COALESCE(@images + ',', '') + image_name
FROM images_table


SELECT Stuff((SELECT ',' + ImageName From dbo.tbl_ProductImage Where ProductId = @id FOR XML PATH('')),1,1,'') as Images


这篇关于如何通过sqlserver以单独的逗号在一个变量中返回图像名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆