3

Assume my kdb+ database has a few tables. How can I export all tables to csv files where the name of each csv is same as the table name?

Gavin Chan
  • 55
  • 8

2 Answers2

7

There may be a number of ways to approach this, one solution could be:

 q)t1:([]a:1 2 3;b:1 2 3)
 q)t2:([]a:1 2 3;b:1 2 3;c:1 2 3)
 q){save `$(string x),".csv"} each tables[]
   `:t1.csv`:t2.csv

ref: http://code.kx.com/q/ref/filewords/#save

If you wish to specify the directory of the file being saved down then you could enhance the function like so:

q){[dir;tSym] save ` sv dir,(`$ raze string tSym,`.csv)}[`:C:/Users/dhughes1/Documents;] each tables[]
  `:C:/Users/dhughes1/Documents/t1.csv`:C:/Users/dhughes1/Documents/t2.csv
Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36
  • 4
    Note that it would get a lot more complex than this if you're talking about a historical database with date-partitioned/splayed tables etc. – terrylynch Apr 03 '17 at 14:56
0

An alternative method to save is to use 0: to prepare text, specifying a delimiter of ",":

q)tab:([]a:1 2 3;b:`a`b`c)
q)show t:","0:tab
"a,b"
"1,a"
"2,b"
"3,c"

And again to save text:

q)`:tab 0: t
`:tab

The advantage of this method is that the delimiter can be specified before saving to disk.

Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36