我正在创建一个存储过程,以简单地将多个记录合并为Microsoft SQL Server中的一个字符串。 这里的样本表看起来像:
表产品:
ProductID Name
----------------------------
5454 Apple
5335 Television
表 CategoryProduct :
CategoryProductID CategoryName
-----------------------------------
1 Food
2 Electronic
3 Healthy
4 Home
表 CategoryProductOnProduct
ID CategoryProductID ProductID
-----------------------------------------
1 1 5454
2 3 5454
3 2 5335
4 4 5335
代码如下:
CREATE PROCEDURE getproductdetails(@idproduct)
AS
BEGIN
DECLARE @Category AS varchar(2048)
IF @idproduct > 0
SET @Category = (
DECLARE @val VARCHAR(MAX);
SELECT @val = COALESCE(@val + ', ' + cp.CategoryName, cp.CategoryName)
FROM
(SELECT CategoryProduct.CategoryName
FROM CategoryProduct
LEFT JOIN CategoryProductOnProduct ON CategoryProduct.CategoryProductID = CategoryProductOnProduct.CategoryProductID
WHERE CategoryProductOnProduct.ProductID = @idproduct) cp
SELECT @val;
);
SELECT
*, @Category as CategoryProduct
FROM
Product
WHERE
Product.ID = @idproduct
ELSE
SELECT
*
FROM
Product
END
GO
如果将@idproduct
参数设置为5454,如何获得结果如下记录?
ProductID Name CategoryProduct
----------------------------------------------
5454 Apple Food, Healthy
预先感谢