Concatenating records in a single column without looping?

前端 未结 5 849
南方客
南方客 2021-01-06 08:27

I have a table with 1 column of varchar values. I am looking for a way to concatenate those values into a single value without a loop, if possible. If a loop is the most e

相关标签:
5条回答
  • 2021-01-06 08:48

    Probably dated now but check out Adam Machanic's post on the topic.

    And this one is certainly dated; I wrote it in 2004.

    Why do I prefer a function over "keeping it inside a SQL query"? Because you'll probably have to do this more than once. Why not encapsulate that code into a single module instead of repeating it all over the place?

    0 讨论(0)
  • 2021-01-06 08:59

    try this:

    DECLARE @YourTable table (Col1 int)
    INSERT INTO @YourTable VALUES (1)
    INSERT INTO @YourTable VALUES (2)
    INSERT INTO @YourTable VALUES (30)
    INSERT INTO @YourTable VALUES (400)
    INSERT INTO @YourTable VALUES (12)
    INSERT INTO @YourTable VALUES (46454)
    
    SELECT
        STUFF(
                 (
                      SELECT
                          ', ' + cast(Col1 as varchar(30))
                          FROM @YourTable
                          WHERE Col1<=400
                          ORDER BY Col1
                          FOR XML PATH('')
                 ), 1, 2, ''
             )
    

    OUTPUT:

    -------------------
    1, 2, 12, 30, 400
    
    (1 row(s) affected)
    
    0 讨论(0)
  • 2021-01-06 09:02

    If it is MySQL, you can use GROUP_CONCAT

    SELECT a, GROUP_CONCAT(b SEPARATOR ',') FROM table GROUP BY a;

    0 讨论(0)
  • 2021-01-06 09:05

    I just tackled a problem like this and looping took forever. So, I concantenated the values in the presentation medium (in this case Crystal Reports) and it was very fast.

    Just an idea.

    0 讨论(0)
  • 2021-01-06 09:08

    declare @concat varchar(max) set @concat = ''

    select @concat = @concat + col1 + ',' from tablename1

    0 讨论(0)
提交回复
热议问题