convert a roow of data under a single column heading

  • I have a table Number with following columns

    ID               Number 1             Number 2            Number 4

    1                   100                    200                  300

    2                   101                    201                  301

    I need to get all numbers where ID =1 under a new table under a single column

    Like below

    Numbers

    100

    200

    300

     

     

     


    Kindest Regards,

    Pavas

    Dream The Dream
    Explore the World
    Experince The Exhilaration

  • SELECT [Number 1] AS [Number] FROM [Number} WHERE [ID] = 1

    UNION ALL

    SELECT [Number 2] AS [Number] FROM [Number} WHERE [ID] = 1

    UNION ALL

    SELECT [Number 3] AS [Number] FROM [Number} WHERE [ID] = 1

    Or if there a lot of columns you could do a loop and use dynamic sql

    Far away is close at hand in the images of elsewhere.
    Anon.

  • Thanks David!


    Kindest Regards,

    Pavas

    Dream The Dream
    Explore the World
    Experince The Exhilaration

  • yes we can do a loop.

    But if My number table is #Number table 'a # table in stored procedure'

    Then how can i find the loop termination value.i.e till how many times i have to execute the loop.


    Kindest Regards,

    Pavas

    Dream The Dream
    Explore the World
    Experince The Exhilaration

  • OK assuming by your first post that

    1. You do not know how many columns are in the table

    2. The numbers in the column names are not consecutive

    3. ID is always the first column

    4. All the other columns are named [Number n]

    SELECT COUNT(*) FROM tempdb.dbo.syscolumns WHERE [id] = object_id('tempdb.dbo.#Number')

    will give you the number of columns in the table

    loop using @colid from 2 to count above

    SET sql = 'SELECT [' + [name] + '] AS [Number] FROM [#Number} WHERE [ID] = 1'

    FROM tempdb.dbo.syscolumns

    WHERE [id] = object_id('tempdb.dbo.#Number')

    AND colid = @colid

    execute the sql

    Far away is close at hand in the images of elsewhere.
    Anon.

  • Thanks David this was really a nice reply.!It worked


    Kindest Regards,

    Pavas

    Dream The Dream
    Explore the World
    Experince The Exhilaration

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply