INSERT SELECT not working

风流意气都作罢 提交于 2019-12-11 03:18:52

问题


Using Informix 11.7, I'm trying to execute a INSERT SELECT query with jdbc positional parameters in the select statement like this :

INSERT INTO table1(id, code, label) 
SELECT ?, ?, ? FROM table2
WHERE ...

Parameters are set like this :

 stmt.setString(1, "auniqueid");
 stmt.setString(2, "code");
 stmt.setString(3, "coollabel");

I get the following error :

Exception in thread "main" java.sql.SQLException: A syntax error has occurred.

When positional parmeters "?" are placed elsewhere it works fine. I have not this problem using PostgreSQL. What's wrong with my query ? I use the Informix JDBC Driver v3.70 JC1.

Thanks for your help.


回答1:


Warning: I have no experience with Informix, answer is based on general observations

When specifying parameters the database will need to know the type of each parameter. If a parameter occurs in the select-list, then there is no way for the database to infer the type of the parameter. Some database might be capable of delaying that decision until it actually receives the parameters, but most database will need to know this at parse time. This is probably the reason why you receive the error.

Some databases - I don't know if this applies to Informix - allow you to cast parameters. So for example:

SELECT CAST(? AS VARCHAR(20)), CAST(? AS VARCHAR(10)), CAST(? AS VARCHAR(5)) FROM ...

In that case the database will be able to infer the parameter types and be able to parse the query correctly.

With this I do assume you are not trying to specify columnnames for the select-list using parameters, as that is not possible.




回答2:


Are you expecting to get column names specified via the placeholders? If so, you're on a hiding to nothing; you cannot use placeholders for structural elements of a query such as column or table names. They can only ever replace values. If you want dynamic SQL to specify the columns, use dynamic SQL; create a string with the content:

INSERT INTO table1(id, code, label)
    SELECT auniqueid, code, coollabel
      FROM table2
     WHERE ...

and work with that.

If those placeholders were going to be values, then you'd be inserting the same values over and over, once for each row returned by the query, and that normally isn't what you'd want; you'd simply insert one row with a VALUES clause, where placeholders are permitted:

INSERT INTO table1(id, code, label) VALUES(?, ?, ?);

That would work fine.

AFAIK, this behaviour conforms to the SQL standard. If it works differently in PostgreSQL, then PostgreSQL has provided an extension to the standard.



来源:https://stackoverflow.com/questions/14650288/insert-select-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!