TSQL Comma Separation

前端 未结 7 1914
夕颜
夕颜 2020-12-10 20:12

I\'m writing an export function, where I need to export contacts to Excel, and I\'ve run into a technical snag - or perhaps a gap in my SQL skills is closer to the truth. ;)

7条回答
  •  我在风中等你
    2020-12-10 20:52

    You can write a function which outputs the roles as comma separated string when you pass it contact id. Then call this function in your select statement :)

    For example if you want to fetch products that are ordered by a customer in a particular order you can use this code:

        create function FetchProducts(@orderid int) returns varchar(1000)
        as
        begin
        declare prods cursor for select ProductName from products where 
                productid in (select ProductId from [Order Details] 
                  Where OrderId = @orderid)
    
        open prods
    
        declare @products  varchar(1000)
        declare @cp varchar(500)
        Select @products = ''
        fetch prods into @cp
    
        while @@fetch_status = 0
        begin
            SET @products = @products + ',' + @cp
            fetch prods into @cp
        end
    
        close prods
        deallocate prods
    
        return substring(@products, 2, len(@products)-1)
        end
    

    now you can use the function as follows:

        select orderid, orderdate, dbo.FetchProducts(orderid) 
    from orders where customerid = 'BERGS'
    

提交回复
热议问题