如何在SQL中将记录数据合并为一个字符串?

时间:2019-04-19 10:40:52

标签: sql sql-server stored-procedures mssql-jdbc

我正在创建一个存储过程,以简单地将多个记录合并为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

预先感谢

0 个答案:

没有答案