Utsav
Utsav

Reputation: 5918

Check for a column in all tables and if column is present print the table name - kdb

We have 3 tables with below columns in our current namespace

q)t:([] a:`a`b`c; b:1 2 3);
q)s:([] a:`a`b`c; b:1 2 3);
q)z:([] z:`a`b`c; b:1 2 3);

Now we want to search and print all the tables which have column a.

Expected output: `a`s

I have two ugly solution which somewhat works

q){$[`a in cols x;x;]} each tables[];
q){(enlist x) where enlist(`a in cols x)}each tables[];

But looking for better optimal solution.

Upvotes: 0

Views: 516

Answers (2)

SeanHehir
SeanHehir

Reputation: 1593

If this is the sort of thing you would like to parameterise and use again something like the following projection may be of use to you:

f:{[t;c]c!t@/:where each flip(c,:())in/:cols each t}[tables[]];

This function produces the following output

q)f`a
a| s t
q)f`a`b
a| `s`t
b| `s`t`z

So it maps a column name to a list of tables containing that column. This sort of mapping can often be more advantageous than working with simple lists as it allows for quick, legible indexing.

q)coldict:f`a`b
q)coldict[`a]
`s`t

Upvotes: 3

Jorge Sawyer
Jorge Sawyer

Reputation: 1341

It'd be best to use the each right (/:) adverb with in:

q)tables[] where `a in/: cols each tables[]
`s`t

Upvotes: 3

Related Questions