I would like to write an sql statment, that works no matter what data file is wanted. example:
exec sql select * from :variable;
I am getting a SQL0104 Error at the ":" "Token not vaild. Valid Token :(NEW FINAL TABLE UNNEST LATERAL MLTABLE JSON_TABLE"
I tried to do it in different statemenst with "insert into :variable", but I get the same Error. Is it maybe not possible and I have to hard code the databasefile into my code or is there a way around? Thanks
You can't use static SQL with a variable table name.
You'd need to use dynamic SQL via
EXECUTE IMMEDIATEorPREPAREandEXECUTENote that
SELECT * FROM TABLEis not a statement that can be dynamically run. For that matter, a static version doesn't make sense.SELECT ... INTO :myData FROM MYTABLEis a valid static statement, but can't be used dynamically. Instead you'd need to useVALUES (SELECT * from MYTABLE) into :myDatawhich can be run dynamically.Here's an IBM example using dynamic SQL. Note normally you'd see the
FETCHin a loop to return multiple rows, as written this will just return the first row then end. This also show the use of replacement variables?in the statement. Which is a best practice as it prevents SQL injection attacks. However note that you can't use a replacement variable for the table name or column names.