cjm2671
cjm2671

Reputation: 19466

How do I pass a column name into a select in KDB QSQL?

I'm trying to wrap a query into a function so I can call it arbitrarily.

I'm struggling to pass in the column name for the where clause. In the naked QSQL, I can just do select from n where premarketGap > 0, but if I try to wrap it in a function, and pass premarketGap as a symbol, it fails.

How do I do it?

Here are my various attempts:

QSQL:

mq: {[data;column;center;width] select from data where (column > (center - width)) and (column < (center + width))}

Functional SQL attempt:

mq:{[data;column;center;width] ?[data;(column > (center - width)),(column < (center + width));();()]}

Calling function:

mq[n;`premarketGap;0.43;0.05]

Naked functional attempt:

?[n;(`premarketGap > 0);();()]

Upvotes: 0

Views: 349

Answers (1)

Matt Moore
Matt Moore

Reputation: 2775

You can use parse to help form functional qsql queries:

parse "select from data where (column > (center - width)) and (column < (center + width))"
?
`data
,,(&;(>;`column;(-;`center;`width));(<;`column;(+;`center;`width)))
0b
()
q)
/ remove the backticks from center, width and column as they are presumed to be columns by parse

?[`data;enlist (and;(>;column;(-;center;width));(<;column;(+;center;width)));0b;()]

https://code.kx.com/q/ref/parse/

Upvotes: 4

Related Questions