2

Somehow, I can only find examples that show how to add one column.

So I have written this code, which works, but I know there is a much better way to do this: table t already exists with columns filled with data, and I need to add new columns that are initially null.

 t: update column1:` from t;
 t: update column2:` from t;
 t: update column3:` from t;
 t: update column4:` from t;

I tried making it a function:

 colNames:`column1`column2`column3`column4;
 t:{update x:` from t}each colNamesList;

But this only added one column and called it x.

Any suggestions to improve this code will be greatly appreciated. I have to add a lot more than just 4 columns and my code is very long because of this. Thank you!

Donald_W
  • 1,773
  • 21
  • 35
Hopper06
  • 89
  • 2
  • 10

1 Answers1

5

Various ways to achieve this....

q)newcols:`col3`col4;

q)@[tab;newcols;:;`]
col1 col2 col3 col4
-------------------
a    1
b    2
c    3

Can also specify different types

q)@[tab;newcols;:;(`;0N)]
col1 col2 col3 col4
-------------------
a    1
b    2
c    3

Or do a functional update

q)![`tab;();0b;newcols!count[newcols]#enlist (),`]
`tab
terrylynch
  • 11,844
  • 13
  • 21
  • Thank you so much for your thorough reply! Functional update I have used, but what is the function with the @[] called? I'd like to know the name of it so I can read more about it. – Hopper06 Oct 10 '14 at 15:25
  • It's the "apply" function (in conjunction with q doing some helpful things under the covers - such as filling the atomic ` out to the same length as the table) http://code.kx.com/wiki/JB:QforMortals2/functions#Functional_Forms_of_Amend – terrylynch Oct 10 '14 at 15:50