Reputation: 49
I'm writing a kdb/q script which will somehow have to prompt for user input and then add that input into several otherwise-preformatted queries. Suggestions on how to prompt/accept the input and parameterize the queries?
Upvotes: 2
Views: 1351
Reputation: 3229
You can pass the input as command-line arguments too, using .z.x
& .Q.opt
:
$ q -item cam
q)p:.Q.opt .z.x
q)p`item
item| "cam"
q)select from tab where items=first `$p`item
items sales prices
------------------
cam 0 15
Upvotes: 4
Reputation: 5644
You can accept user input using read0 0
, which waits will catch all a user types until they hit enter. The input will then be returned as a string. You can either type this into an active q session or wrap it up in a function like this:
q)f:{a:read0 0;show a}
q)f[]
12
"12"
In this case I have typed 12
which is returned as the string "12"
.
As for parameterising queries this can be done through strings, but this is not very q so to speak. You would be better to cast the inputs to another type and use functional form or even standard selects, for example:
q)tab:([]a:1 2 3 4)
q){input:"J"$read0 0;select from tab where a=input}[]
4
a
-
4
You can read more about functional form on the Kx wiki.
Upvotes: 3
Reputation: 131
For user input, you can use read0
on file handle 0
- standard input. User prompt would be printed to standard output (file descriptor 1
) like this:
1 "Please give me some input: ";
input: read0 0;
For query parametrization, you can go either with string concatenation of functional query form as described here (code.kx.com)
Upvotes: 2