Written by

Senior Startups and Community Programs Manager at InterSystems Corporation
Question Evgeny Shvarov · May 19, 2020

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

Robert Cemper · May 20, 2020

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

 

0
John Murray  May 20, 2020 to Robert Cemper

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.

0
Vitaliy Serdtsev · May 20, 2020

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
0
Benjamin De Boe  May 20, 2020 to Vitaliy Serdtsev

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.

0
Evgeny Shvarov  May 24, 2020 to Benjamin De Boe

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.

0
Danny Wijnschenk · May 20, 2020

Use %SQL.Statement for dynamic sql, do not use %ResultSet anymore (it is slower).

0