I'm attempting to declare a query string to execute in MonetDB. The documentation is not clear if this is possible, but other engines allow this functionality (such as MySQL and MS SQL Sever). Trying the following
execute 'select * from tables';
fails with the message
Error: syntax error, unexpected STRING, expecting IDENT or sqlINT
The reason behind this is that I need to declare a variable schema name, such that I can execute a query in the following way:
declare s varchar(32);
set s = 'the_schema';
execute 'select * from ' || the_schema || '.the_table';
Please let me know if this is even possible in MonetDB or if you have some tips about that. I tried with a prepared statement, as given in MonetDB's documentation -- but the following code cannot execute
prepare 'select * from ' || the_schema || '.the_table';
because prepare
expects an actual query, not a string.
Edit
I'd like to achieve this with only SQL stored functions. The client I have has to execute the SQL functions directly, and there's no intermediate Java/PHP/etc scripts to build the SQL on the fly before they're being sent to MonetDB server. Thus, I should create a function like so:
create function getData( dataSchema varchar(32) )
returns bigint
begin
declare query varchar(128);
set query = 'select count(*) from ' || dataSchema || '.the_table';
return( execute query );
end;
My function is more complicated than this, with other tables and even functions. The issue is that functions belong to one schema, and data tables belong to another schema, which is not known in 'compile' time.
Unfortunately, MonetDB does not support this.
If the only varying parts of the constructed query are values, you could try PREPARE:
sql>PREPARE SELECT * FROM foo WHERE id = ?;
execute prepared statement using: EXEC 13(...)
sql>EXEC 13(22);
But it is not possible to for example write FROM ?
. For that kind of thing, the only alternative is to do the string concatenation client side.