Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Everyone,

How to create columns dynamically in sqlserver.i have created a table with the columns A,B and C.

a b c
1 2 3
2 4 5
3 5 6


i am reading data from excel and inserting into the table, let suppose i am getting three columns from excel then there is no issue. if am getting more than three columns i have to find out the new column
and alter the table according to it and need to insert the data like below mentioned example.

a b c D E
1 2 3
2 4 5
3 5 6
1 2 3 5 6
2 4 5 8 9
3 5 6 7 4


if anyone knows,kindly help me how to do the same.



thanking you,
Posted

1 solution

I would suggest that you do not add columns to the table at runtime. Instead you have two possibilities.

1. You can decide the amount of columns beforehand. Loop through the data and see how many columns you need. Then when adding the data, leave the empty values in in the insert statement as null.

2. Re-model you database structure. Instead of storing the data in Excel columns as DB columns, transpose the data to be rows. This would mean that you would have table something like (pseudo definition):
- rownumber
- columnnname
- value

So the rows from your example could be:
rownumber columnname value
--------- ---------- -----
1         a          1
1         b          2
1         c          3
2         a          2
2         b          4
...
4         a          1
4         b          2
4         c          3
4         d          5
4         e          6
...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900