在sql数据库中用逗号分隔的多行值

时间:2016-06-21 16:19:18

标签: asp.net sql-server stored-procedures

我有一个电子商务网站,一个ID可以有多个产品订单。截至目前我有这个:

enter image description here

如你所见,它显示了我桌上的减少量。我希望有一个输出:

Carbon Dixode, Industrial Oxygen

因为它们位于相同的ID(10)。

同样如此
Compressed Air, Kerosene, Medical Oxygen

这是我的代码背后:

private void GetOrderList()
    {
        ShoppingCart k = new ShoppingCart()
        {
            Flag = 0
        };
        DataTable dt = k.GetOrderList();

        gvCustomerOrders.DataSource = dt;
        gvCustomerOrders.DataBind();
        gvCustomerOrders.HeaderRow.TableSection = TableRowSection.TableHeader;
    }

这是GetOrderList()

internal DataTable GetOrderList()
    {
        SqlParameter[] parameters = new SqlParameter[1];
        parameters[0] = DataLayer.DataAccess.AddParameter("@Flag", Flag, System.Data.SqlDbType.Int, 20);
        DataTable dt = DataLayer.DataAccess.ExecuteDTByProcedure("SP_GetOrderList2", parameters);
        return dt;
    }

这是存储过程:

ALTER procedure [dbo].[SP_GetOrderList2]
(
@Flag int
)
AS
BEGIN
    BEGIN TRY

    if(@Flag <>0)
    Begin
        Select *
        FROM CustomerDetails where Id=@Flag;

    End
    else
    begin
        select p.[name],cd.Id, cd.CustomerName, cd.CustomerEmailID,cd.CustomerPhoneNo,cd.CustomerAddress,cd.TotalPrice,cd.OrderDateTime, cd.PaymentMethod FROM CustomerDetails cd Inner Join CustomerProducts cp ON cp.CustomerID = cd.Id Inner Join Products p ON cp.ProductID = p.ProductID
    end


    END TRY

    BEGIN CATCH

        PRINT('Error Occured')
    END CATCH

    END

我真正想要的是避免在我的桌子上减少。我希望同一ID上的产品保持在一起,因为我的价格已经合并。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

您可以使用group_concat()函数来实现此目的。试试这个示例查询。

选择 id,name,phoneno,email,group_concat(product),price 来自<TABLE_NAME> GROUP BY phoneno

谢谢。

答案 1 :(得分:0)

1

1&gt; DECLARE表变量

declare @Table Table(RecID int identity,Id int,Product nvarchar(50))

2&gt;插入唯一值..

insert into @Table
select distinct id,Product from CustomerDetails 

3&GT;声明一些变量

declare @i int,@cnt int,@Id int
declare @Product VARCHAR(Max) 
select @cnt=count(*),@i=1 from @Table
while @i<=@cnt
begin
select @Id=id from @Table where RecID =@i
set @Product =''
SELECT  @Product = COALESCE(@Product + ',', '') + Product 
FROM CustomerDetails where id=@id
update @Table set Product =@Product where id=@id
set @i=@i+1
end

4&gt;用表变量选择你的表..

select distinct d.id,d.name,d.phoneno,d.email,t.product
from CustomerDetails d
join @Table t on t.id=d.id
.

答案 2 :(得分:0)

确定。

您可以在If secttion ..

中添加新代码
----your code
if(@Flag <>0)
    Begin
       declare @Product VARCHAR(Max)
       SELECT  @Product = COALESCE(@Product + ', ', '') + Product 
       FROM CustomerDetails where Id=@Flag;
        ----select your entire field except product column.  In product columns you have only select `---@Product`  
     select distinct id, name, phoneno, email ,@Product  product
      from CustomerDetails where Id=@Flag;

    End
-----your code

@Product变量中,您的产品列数据将以逗号连接。根据{{​​1}}。

如果您还想在其他部分中使用它,那么您必须按照我之前的答案进行操作..