简体   繁体   中英

SQLExceptionHelper Invalid Input syntax for integer (PL/pgSQL)

I want to get an integer from a database query:

SELECT CAST(concat('id_',substr_of_jointable) AS INTEGER) into integervalue 
  FROM books_authors where id_books = booksvalue 
  ORDER BY id_books DESC 
  LIMIT 1;

subsr_of_jointable is a TEXT with value authors . However I always get an error:

ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: invalid input syntax for integer: "id_authors"
Wobei: SQL statement "SELECT CAST(concat('id_',substr_of_jointable)AS INTEGER) FROM books_authors where id_books = books_value ORDER BY id_books DESC LIMIT 1"
PL/pgSQL function books_ins_trig_proc() line 125 at SQL statement

Does anyone have an idea why? The column id_books id_authors is an integer value in the database.

Assuming you're trying to build a dynamic query inside a PL/pgSQL function, you might want to take a look at this approach.

Data sample

CREATE TABLE t (id_authors INT);
INSERT INTO t VALUES (1);

Function

CREATE OR REPLACE FUNCTION myfunction(TEXT) RETURNS INT 
LANGUAGE 'plpgsql' AS $BODY$
DECLARE i INT;
BEGIN
  EXECUTE 'SELECT id_'|| $1 ||' FROM t LIMIT 1;' INTO i;
  RETURN i;
END;
$BODY$;

This example is only to shows how you can concatenate your strings to create a column name inside your dynamic query.

Calling the function

SELECT * FROM myfunction('authors');

 myfunction 
------------
          1
(1 Zeile)

Further reading:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM