Search code examples
sqlt-sqlsap-iq

Determine all columns from a table and write them separated by commas in a variable


--Dummy table
create table table1 (
column_order varchar (100)
)

insert into table1 values ('column1')
insert into table1 values ('column2')
insert into table1 values ('column3')
insert into table1 values ('column4')
insert into table1 values ('column5')
insert into table1 values ('column6')

--Start of select

declare @rowsCount INT
declare @i INT = 1
declare @column varchar(1000) = ''

set @rowsCount = (select COUNT(*) from table1)

while @i <= @rowsCount
begin
 set @column = @column + (select column_order from table1 where rowid(table1) = @i) + ', '
 set @i = @i + 1
end
select @column

This code has the function ROWID thats an IQ-Sybase funktion, and im not sure what other DBMS can use it. And above you have a example what i want my select to look like.

My problem is, you cant use the ROWID function with sys.column or any other systables. Has anyone an idea how to get the same select as mine without using the ROWID function.

If you are using IQ, i constructed the code so you can just type f5 and see the select statement, after that just drop the dummy table.


Solution

  • Use list(). It works in both the ASA system and IQ catalogs.

    drop table if exists table1
    go
    
    create local temporary table table1 (
    column_order varchar (100)
    ) in system --create table in system
    
    insert into table1 values ('column1')
    insert into table1 values ('column2')
    insert into table1 values ('column3')
    insert into table1 values ('column4')
    insert into table1 values ('column5')
    insert into table1 values ('column6')
    
    declare @columns varchar(100)
    
    select @columns = list(column_order) from table1
    
    select @columns
    go