SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software Kodyaz Development Resources
Development resources, articles, tutorials, samples, codes and tools for .Net, SQL Server, Vista, etc.

Can I "flatten" multiple rows into one line in a #temp table?

Last post 07-27-2012, 8:09 AM by miteshaegis. 2 replies.
Sort Posts:
  •  06-06-2012, 12:38 AM 34249

    Can I "flatten" multiple rows into one line in a #temp table?

    I have a table containing notes for leads like this:
    ID DATE NOTE
    --- ---------- ------------------------
    10 1/1/12 New Lead
    10 2/8/12 set meeting
    15 2/4/12 New Lead
    15 3/9/12 set meeting
    15 5/7/12 signed contract

    I would like to create a #temp table in a Stored Proc that holds the data like this:
    ID NOTE
    ---- --------------------------------------------------------------------------
    10 1/1/12: New Lead | 2/8/12: Set Meeting
    15 2/4/12: New Lead | 3/9/12: Set meeting | 5/7/12: signed contract

    where I concatenate the date+': '+ note+' | '+... and the next date, note, etc for as many rows as there are for a given ID in the original notes table (there may be different # of rows for different IDs, obviously)...
    Is this possible?

    Thanks in advance!
  •  07-12-2012, 4:57 AM 34298 in reply to 34249

    Re: Can I "flatten" multiple rows into one line in a #temp table?

    Hello ncccapt,
    Please review the SQL concatenation tutorial at http://www.kodyaz.com/articles/concatenate-using-xml-path.aspx

    And here is sample sql concatenate query that will help you solve your question.

    select distinct id, stuff( ( select ' | ' + date +': ' + note from #t t2 where t2.id = t1.id for xml path('') ), 1,3, '') note from #t t1
  •  07-27-2012, 8:09 AM 34321 in reply to 34249

    Re: Can I "flatten" multiple rows into one line in a #temp table?

    We want to display record in one line in sql than use the select query in sql server.

    select table id, stuff( ( select ' | ' + date +': ' + note from #t t2 where t2.id = t1.id for xml path('') ), 1,4, '') note from #table table1

View as RSS news feed in XML
Copyright © 2004 - 2013 Eralper Yilmaz. All rights reserved.
Community Server by Telligent Systems