Yes you are right - the #__tablename syntax seems to work ok in simple SQL statements, but when used in SET @targettable=“#__tablename” it doesn’t.
Since the simple version works Joomla must be doing some processing of the script file rather than passing it straight to the database, but it seems to fail when the #__tablename is in a SET statement.
I have tried both double and single quotes and also without quotes around it.
With no quotes the SQL fails with “Unknown column ‘#__tablename’ which makes sense as Joomla isn’t touching it and SQL thinks it must be a column name not a string since it hasn’t got quotes around it.
With either type of quote you get the original error which presumably is when SQL tries to parse the CONCAT statement that includes @tablename as a non existent table. Being hidden in a prepared statement the error message is a little obscure.
So the question is whether this is a flaw in the design of the Joomla installer. It is not universally replacing “#_” with the table prefix, only if it is in the body of a simple statement like SELECT ALTER INSERT UPDATE or DROP?
The reason for using a prepared statement is that is AFAIK the only way to test if a column exists without having to create a stored procedure on the database. (This site is still on MySQL5.7, v8 might have a better solution)
Perhaps this discussion needs to move to bugs? It seems to me that Joomla should replace #_ with the prefix wherever it appears.
Thanks for considering the problem
Roger