kdb+parameterization

Parameterizing a kdb q script


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?


Solution

  • 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.