Results 1 to 9 of 9

Thread: select

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Aug 2000
    Posts
    617

    select

    Hello Guys/Gals

    Would like to select 5 items from a table

    ids
    1
    2
    3
    4
    5

    and concatenate them to return
    1 2 3 4 5

    any ideas? Could that be done in 1 select statement?

    Thanks in advance...

  2. #2
    RoyceWindsor1
    Guest
    I think this will work, but I have to believe there's a better way to do what you're trying to do...
    Code:
    -- Untested...
    SELECT 'idstring' = a.id + b.id + c.id + d.id + e.id
    FROM
    myTable as a
    LEFT JOIN
    myTable as b
    ON
    b.id = 2
    LEFT JOIN
    myTable as c
    ON
    c.id = 3
    LEFT JOIN
    myTable as d
    ON
    d.id = 4
    LEFT JOIN
    myTable as e
    ON
    e.id = 5
    WHERE
    a.id = 1

  3. #3
    RoyceWindsor1
    Guest
    Actually, you'll have to do a CONVERT on each of those id's before you can concatenate them

  4. #4

    Thread Starter
    Fanatic Member
    Join Date
    Aug 2000
    Posts
    617

    5

    5 was just a number picked at random.... It could have been 2000

    I'd like to do this (if possible without using a cursor)

    Thanks

  5. #5
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333
    You want to select potentially 2000 separate items from one table, and concatenate the results into one string????

  6. #6

    Thread Starter
    Fanatic Member
    Join Date
    Aug 2000
    Posts
    617

    Thanks

    Thanks guys,

    I actually figured it out...

  7. #7
    RoyceWindsor1
    Guest
    How did you do it?

  8. #8
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333
    I'm curious. What did you wind up doing?

  9. #9

    Thread Starter
    Fanatic Member
    Join Date
    Aug 2000
    Posts
    617

    2 ways

    1. Using a cursor
    2. With no cursor

    1.
    declare alltogether cursor for
    select id from test

    declare @concatenatevals varchar(4000)
    set @concatenatevals = ' '
    declare @ID int

    open alltogether
    fetch next from alltogether into @ID
    while (@@Fetch_Status = 0)
    begin
    set @concatenatevals = @concatenatevals + ' ' + convert(varchar(10),@ID)
    fetch next from alltogether into @ID
    end


    print @concatenatevals
    close alltogether
    deallocate alltogether

    2.

    declare @moi varchar(255)
    select @moi = ' '
    SELECT @moi = COALESCE(@moi + convert(varchar(10),id), " ") + " "
    FROM test
    print @moi


    granted I may have a little extra in the second solution
    Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width