Select Include Field Names

  • How can I include the column headers (field names) AND the data in a table in a single select statement.  For instance, lets say I have a table called SampleTable with a single Field SampleField.  It has 2 rows of data, dog and cat.

    If I did SELECT * FROM  SampleTable the result would be:

    dog

    cat

    How could I get the result?

    SampleField

    dog

    cat

     

     

  • I'm not sure I understand the question - where do you want to use the field name ?! In your application code ?!

    If you do your select * in query analyzer you will see the column header!

    confusing question....







    **ASCII stupid question, get a stupid ANSI !!!**

  • SELECT * returns the data in the table.  What I'd like is the data and the column headers as data.

    So in query analyzer, the results normally would look like this:

    SampleField (header)

    dog

    cat

    What I'm trying to do is getting it looking like this:

    SampleField (header)

    SampleField (data)

    dog

    cat  

     

  • SELECT 'SampleField' AS SampleField

    UNION ALL

    SELECT SampleField

    FROM ...

    Note however that this requires the data in the column SampleField to be of the varchar (or similar) type.

  • And since I am anticipating a follow-up question, if you need the row with the column name to be the first one in the result set you should add an ORDER BY like this:

    ORDER BY CASE WHEN SampleField = 'SampleField' THEN 1 ELSE 2 END

    Note that in order to add this ordering you need to wrap the union statements in a derived table and then order that output. Like this:

    SELECT SampleField

    FROM (

    ...

    UNION ALL

    ...

    ) foo

    ORDER BY ...

    Now the real question is why do you need this?

  • I'm using it to compare the data of two rows in five large tables.  The first row of data I'm pulling is data in the system from where the user manually entered data into the application.  The second row is where I'm sending the data via an interface from another program.

    It gets pretty complicated trying to explain the issues involved in this interface, but the purpose of this is to test the results, visually.

    You gave me enough that I can make this work.  Thanks.

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

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