Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add 50 columns to table variable

I would like to add around 50 columns to table defined as variable. Names of those columns are coming from another table and basically they are just numbers - DEPA_KEY. (department key)

Is it possible to add those columns dynamically with loop or something similar?

Table defined as variable (here I would like dynamically add 50 columns):

DECLARE @USERS TABLE
(
  USER_KEY INT,
  USDE_HSU DECIMAL(8,2)
)

Query for all departments:

SELECT DEPA_KEY FROM CADEPA
like image 315
FrenkyB Avatar asked Aug 11 '26 00:08

FrenkyB


1 Answers

AFAIK, You can't change the structure of a table variable:

DECLARE @T AS TABLE
(
    col1 int
);

ALTER TABLE @T 
    ADD col2 char(1)       
;

This will generate an error.

You can, however, do it with a temporary table:

CREATE TABLE #T 
(
    col1 int
);

ALTER TABLE #T 
    ADD col2 char(1)
;    
like image 146
Zohar Peled Avatar answered Aug 13 '26 17:08

Zohar Peled



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!