add column dynamically with select query

16.5k views Asked by At

I have one table which has 20 columns default

These 20 columns named as D1 D2 D3...D20 , now with select query i want to add the other columns dynamically.. for ex D21 D22...D31, so how can i write a query to add this columns dynamically with incremented value..max limit is 31,please help

default table columns
D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 D14 D15 D16 D17 D18 D19 D20

now i want to add columns in continuity to D20 i.e D21 and so on upto D31 , while selecting this columns the other column i.e fro D21 to D31 also get added and selected

query is

select * ,'  ' as D21 from tbl1

this will give me all 20 columns upto D20 and one additional D21 i want it upto D31 without hardcoding other column name

3

There are 3 answers

0
Indranil.Bharambe On BEST ANSWER

try below code

declare @a int =21
Declare @sql varchar(max)='select *,'
while @a <32
begin
set @sql = @sql + cast(@a as varchar) + ' as D' + cast(@a as varchar) + ' ,'

set @a = @a+1

end
set @sql = substring(@sql,0,len(@sql)-1) + ' from tbl1'

 exec( @sql)
0
Dan On

Using dynamic SQL, you can do something like this:

DECLARE @SQL AS NVARCHAR(MAX) = 'select *';

WITH Numbers (N) AS 
(
    SELECT ROW_NUMBER() OVER (ORDER BY object_id) N FROM sys.all_objects
)
SELECT @SQL = @SQL + ', ''  '' as D' + CAST(N AS NVARCHAR) 
FROM Numbers WHERE N BETWEEN 21 AND 31;

SET @SQL = @SQL + ' from tbl1';

EXEC sp_executesql @SQL
0
ChiranjeeviIT On

if you want to write only with SQL query

Hope it might work for you.

 with sample as 
       (SELECT 1 + LEVEL-1 idx  
        FROM dual CONNECT BY LEVEL <= 31) 
   select  listagg('D'||idx, ',') 
   within group (order by idx) as list 
   from sample 
   where idx >= 21

please let us know if it works for you.

Thanks and Regards, Chiranjeevi.