Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Database & SysAdmin
  3. Database
  4. Select statement: ordering by column name.

Select statement: ordering by column name.

Scheduled Pinned Locked Moved Database
databasexmlquestion
15 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Septimus Hedgehog

    To keep this simple. Let's say I have a table with three columns called mineral, vegetable, animal. Is it possible to select this table's records and list them in column order animal, mineral, vegetable? I know I can do it by specifying the column names like "select animal, mineral, vegetable from whatever" but I have some tables that have an awful lot of columns and sometimes it's easier to navigate the records if I have all the columns displayed but alphabetically using something that might be discovered from the schema where the columns are defined. Hope that makes sense. Edit: The following statement sort of shows what I have in mind from the schema. SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tablenamehere' ORDER BY column_name

    If there is one thing more dangerous than getting between a bear and her cubs it's getting between my wife and her chocolate.

    G Offline
    G Offline
    GuyThiebaut
    wrote on last edited by
    #6

    This will do the trick for one table. Just build another cursor around this cursor to do it by table. (my Jedi senses tell that I am going to get flamed by someone for suggesting a cursor)

    DECLARE curs CURSOR FOR
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'yourTable'
    ORDER BY column_name

    declare @qry as nvarchar(max)
    set @qry = 'select '

    DECLARE @col nvarchar(max)

    OPEN curs
    FETCH NEXT FROM curs into @col
    WHILE @@FETCH_STATUS = 0
    BEGIN
    set @qry += '['+@col + '],'
    FETCH NEXT FROM curs into @col
    END

    CLOSE curs
    DEALLOCATE curs

    set @qry = substring(@qry,1,len(@qry)-1) + ' from yourTable'

    exec(@qry)

    “That which can be asserted without evidence, can be dismissed without evidence.”

    ― Christopher Hitchens

    T 1 Reply Last reply
    0
    • S Septimus Hedgehog

      To keep this simple. Let's say I have a table with three columns called mineral, vegetable, animal. Is it possible to select this table's records and list them in column order animal, mineral, vegetable? I know I can do it by specifying the column names like "select animal, mineral, vegetable from whatever" but I have some tables that have an awful lot of columns and sometimes it's easier to navigate the records if I have all the columns displayed but alphabetically using something that might be discovered from the schema where the columns are defined. Hope that makes sense. Edit: The following statement sort of shows what I have in mind from the schema. SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tablenamehere' ORDER BY column_name

      If there is one thing more dangerous than getting between a bear and her cubs it's getting between my wife and her chocolate.

      D Offline
      D Offline
      David Mujica
      wrote on last edited by
      #7

      Maybe you could build a stored procedure based on the following SQL which gives you the column names in alphabetical order:

      Use [YourDatabase]
      GO

      SELECT SC.NAME FROM SYS.objects SO, SYS.columns SC
      WHERE SO.TYPE = 'U' AND SO.name LIKE '[yourTableName]'
      AND SO.object_id = SC.object_id
      ORDER BY SC.name

      You could use this to create a view or create a Dynamic SQL Statement where you pass in your "where clause". Hope this helps. :thumbsup:

      1 Reply Last reply
      0
      • G GuyThiebaut

        This will do the trick for one table. Just build another cursor around this cursor to do it by table. (my Jedi senses tell that I am going to get flamed by someone for suggesting a cursor)

        DECLARE curs CURSOR FOR
        SELECT COLUMN_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'yourTable'
        ORDER BY column_name

        declare @qry as nvarchar(max)
        set @qry = 'select '

        DECLARE @col nvarchar(max)

        OPEN curs
        FETCH NEXT FROM curs into @col
        WHILE @@FETCH_STATUS = 0
        BEGIN
        set @qry += '['+@col + '],'
        FETCH NEXT FROM curs into @col
        END

        CLOSE curs
        DEALLOCATE curs

        set @qry = substring(@qry,1,len(@qry)-1) + ' from yourTable'

        exec(@qry)

        “That which can be asserted without evidence, can be dismissed without evidence.”

        ― Christopher Hitchens

        T Offline
        T Offline
        Tim Carmichael
        wrote on last edited by
        #8

        In regards to using cursors, yes, they work... mostly. However, I've had issues in the past where they didn't work, so, as ugly as it is, I switched to WHILE loops... Ugly, but it worked consistenly. Tim

        G 1 Reply Last reply
        0
        • T Tim Carmichael

          In regards to using cursors, yes, they work... mostly. However, I've had issues in the past where they didn't work, so, as ugly as it is, I switched to WHILE loops... Ugly, but it worked consistenly. Tim

          G Offline
          G Offline
          GuyThiebaut
          wrote on last edited by
          #9

          You're right - here's the code for all tables using the while version:

          set rowcount 1

          declare @table as nvarchar(max)
          declare @tbl_rowcount as int
          declare @col_rowcount as int
          declare @col nvarchar(max)
          declare @qry as nvarchar(max)

          select @table = table_name
          from information_schema.tables
          order by table_name

          select @tbl_rowcount = @@rowcount

          while (@tbl_rowcount != 0)
          begin

          set @qry = 'select ' + '''' + @table + '''' + ' as tableName, '

          select @col = column_name
          from information_schema.columns
          where table_name = @table
          order by column_name

          select @col_rowcount = @@rowcount

          while (@col_rowcount != 0)
          begin

            set @qry += '\['+@col + '\],'
            
            select @col = column\_name
            from information\_schema.columns
            where table\_name = @table
            and column\_name > @col
            order by column\_name
            
            select @col\_rowcount = @@rowcount
          

          end

          set @qry = substring(@qry,1,len(@qry)-1) + ' from ' + @table
          set rowcount 0
          exec(@qry)
          set rowcount 1

          select @table = table_name
          from information_schema.tables
          where table_name > @table
          order by table_name

          set @tbl_rowcount = @@rowcount

          end

          set rowcount 0

          “That which can be asserted without evidence, can be dismissed without evidence.”

          ― Christopher Hitchens

          1 Reply Last reply
          0
          • S Septimus Hedgehog

            To keep this simple. Let's say I have a table with three columns called mineral, vegetable, animal. Is it possible to select this table's records and list them in column order animal, mineral, vegetable? I know I can do it by specifying the column names like "select animal, mineral, vegetable from whatever" but I have some tables that have an awful lot of columns and sometimes it's easier to navigate the records if I have all the columns displayed but alphabetically using something that might be discovered from the schema where the columns are defined. Hope that makes sense. Edit: The following statement sort of shows what I have in mind from the schema. SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tablenamehere' ORDER BY column_name

            If there is one thing more dangerous than getting between a bear and her cubs it's getting between my wife and her chocolate.

            R Offline
            R Offline
            Ralph D Wilson II
            wrote on last edited by
            #10

            Maybe I missed something in reading through the thread but I'll ask anyway. ;-) What RDBMS are you using? If it is SQL Server (or probably most others) you can create a query that will generate a SELECT statement from the table and column information in the system tables (in SQL Server, sys.tables and sys.columns). Once that is generated (and a DECLAREd variable set to that varchar string, you can execute the r results.

            S 1 Reply Last reply
            0
            • R Ralph D Wilson II

              Maybe I missed something in reading through the thread but I'll ask anyway. ;-) What RDBMS are you using? If it is SQL Server (or probably most others) you can create a query that will generate a SELECT statement from the table and column information in the system tables (in SQL Server, sys.tables and sys.columns). Once that is generated (and a DECLAREd variable set to that varchar string, you can execute the r results.

              S Offline
              S Offline
              Septimus Hedgehog
              wrote on last edited by
              #11

              Good morning, Ralph. The database we use is SQL Server 2008. Is the idea you have in mind different to the other suggestions? If it is do you think you could paste an example for me/us?

              If there is one thing more dangerous than getting between a bear and her cubs it's getting between my wife and her chocolate.

              R 1 Reply Last reply
              0
              • S Septimus Hedgehog

                Good morning, Ralph. The database we use is SQL Server 2008. Is the idea you have in mind different to the other suggestions? If it is do you think you could paste an example for me/us?

                If there is one thing more dangerous than getting between a bear and her cubs it's getting between my wife and her chocolate.

                R Offline
                R Offline
                Ralph D Wilson II
                wrote on last edited by
                #12

                Th following could be implemented as a Sotred Procedure or simply executed as is in a query:

                USE {enter your desired database name here};

                DECLARE @NameOfTable VarChar(128);
                SET @NameOfTable = '{enter your desired table name here}';

                DECLARE @SQLStatement VarChar(8000);

                SET @SQLStatement = 'SELECT ''' + @NameOfTable + ''' AS TableName';

                PRINT @SQLStatement;

                EXEC(@SQLStatement);

                WITH TableColumns_CTE
                AS
                (
                SELECT T.name AS TableName
                ,C.name AS ColumnName
                ,ROW_NUMBER() OVER (PARTITION BY T.name ORDER BY T.name, C.name) Seq
                FROM sys.tables T
                INNER JOIN sys.columns C
                ON T.object_id = C.object_id
                AND T.name = @NameOfTable
                )

                SELECT @SQLStatement = @SQLStatement + ', ' + ColumnName
                FROM TableColumns_CTE;

                SELECT @SQLStatement = @SQLStatement + ' FROM ' + @NameOfTable + ';';

                PRINT @SQLStatement;

                EXEC(@SQLStatement);

                S 1 Reply Last reply
                0
                • R Ralph D Wilson II

                  Th following could be implemented as a Sotred Procedure or simply executed as is in a query:

                  USE {enter your desired database name here};

                  DECLARE @NameOfTable VarChar(128);
                  SET @NameOfTable = '{enter your desired table name here}';

                  DECLARE @SQLStatement VarChar(8000);

                  SET @SQLStatement = 'SELECT ''' + @NameOfTable + ''' AS TableName';

                  PRINT @SQLStatement;

                  EXEC(@SQLStatement);

                  WITH TableColumns_CTE
                  AS
                  (
                  SELECT T.name AS TableName
                  ,C.name AS ColumnName
                  ,ROW_NUMBER() OVER (PARTITION BY T.name ORDER BY T.name, C.name) Seq
                  FROM sys.tables T
                  INNER JOIN sys.columns C
                  ON T.object_id = C.object_id
                  AND T.name = @NameOfTable
                  )

                  SELECT @SQLStatement = @SQLStatement + ', ' + ColumnName
                  FROM TableColumns_CTE;

                  SELECT @SQLStatement = @SQLStatement + ' FROM ' + @NameOfTable + ';';

                  PRINT @SQLStatement;

                  EXEC(@SQLStatement);

                  S Offline
                  S Offline
                  Septimus Hedgehog
                  wrote on last edited by
                  #13

                  Ralph, thank you for that. I appreciate it and will try it at the office tomorrow.:thumbsup:

                  If there is one thing more dangerous than getting between a bear and her cubs it's getting between my wife and her chocolate.

                  R 1 Reply Last reply
                  0
                  • S Septimus Hedgehog

                    Ralph, thank you for that. I appreciate it and will try it at the office tomorrow.:thumbsup:

                    If there is one thing more dangerous than getting between a bear and her cubs it's getting between my wife and her chocolate.

                    R Offline
                    R Offline
                    Ralph D Wilson II
                    wrote on last edited by
                    #14

                    Did that wok for you?

                    S 1 Reply Last reply
                    0
                    • R Ralph D Wilson II

                      Did that wok for you?

                      S Offline
                      S Offline
                      Septimus Hedgehog
                      wrote on last edited by
                      #15

                      Ralph, I completely forgot to try it. I just c&p into ssms but it didn't run clean and throws some errors. I need to schedule some time to look at it, but off the shelf, I couldn't run it even though I replaced the database name and table with correct values.

                      If there is one thing more dangerous than getting between a bear and her cubs it's getting between my wife and her chocolate.

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups