Can I substitute table in FROM with a hosted variable?
Haven't found this in the documentation. I want:
&sql(SELECT name INTO :var FROM :table)Is it possible?
Comments
NO it is not possible:
In IRIS for Windows (x86-64) 2020.1 (Build 215U) it is compiled.
But at run time you get an SQLCODE=1 and an error message for a bad SQL statement.
Better compose an SQL string "SELECT name FROM "_table and process it with some ResultSet class,
The embedded code in the class we know from Cache is gone.
It all generates into a %scqlc.* class
Better compose an SQL string "SELECT name FROM "_table and process it with some ResultSet class
But take care you don't open your system up to an SQL Injection attack.
Extending the reply of @Robert Cemper
- The following query compiles without errors, even though Studio highlights the error
<FONT COLOR="#800080">&sql(</FONT><FONT COLOR="#0000ff">select </FONT><FONT COLOR="#800000">:fieldname </FONT><FONT COLOR="#000080">into </FONT><FONT COLOR="#800000">:fieldvar </FONT><FONT COLOR="#000080">from </FONT><FONT COLOR="#800000">:tablename</FONT><FONT COLOR="#800080">)</FONT>
Everything is fine in Caché: the error occurs at the compilation-time.In order for an error to occur in IRIS Studio too you need to use the flag /compileembedded=1
- It is strange that the documentation mentions field name, but there is no mention of table name:
A host variable cannot be used to pass a field name or keyword into an SQL statement. proof
For more about where the source code for embedded SQL has gone in 2020.1, please see this article on the Universal Query Cache
Indeed funny the doc doesn't call out table names while it does talk about field names, probably because it silently assumes the one implies the other. I'll ask our doc writer to fix that. Thanks for the notification.
Thanks, @Benjamin De Boe ! It doesn't explain though (at least for me) why hosted variables can't be used for table and column names.
I only mentioned the UQC to clarify where source code for embedded SQL went. The use of host variables for table/field names has been addressed in the docs since.
Use %SQL.Statement for dynamic sql, do not use %ResultSet anymore (it is slower).