cancel
Showing results for 
Search instead for 
Did you mean: 

Columns order alphabetically in select result

0 Kudos
773

Hello, I have table with many columns and would like to do select like Select * from table and would like that result of query is alphabetically by column names Is this possible?

Regards

Tomaž

Vlad
Product and Topic Expert
Product and Topic Expert

Will you accept an answer, similar to this one https://stackoverflow.com/a/10498945 where the SQL query will be built at runtime via the stored procedure?

The idea is quite simple, you get all columns from the DB, sort them, create a string and then execute it as an SQL statement.

Accepted Solutions (0)

Answers (1)

Answers (1)

ALTER PROCEDURE "DBA"."SelectWithColumnsOrdered"(in @table_name char(100))
BEGIN
  declare @sql long varchar ;

  select list(cname, ', ' order by cname)
    into @sql
    from sys.syscolumns
   where tname = @table_name ;

  set @sql = 'select ' || @sql || ' from ' || @table_name ;

  execute immediate with result set on @sql  ;
END
VolkerBarth
Contributor
0 Kudos

FWIW, with v17, indirect identifiers often help to omit execute immediate calls - however, I don't know whether they could also be of help for cases like this with a variable number of identifiers (here columns)... - just in case someone has an idea...