2

I want to run a query like this -

"SELECT nextval('sequenceName')"

but before this I want to check that sequenceName exists or not in Hibernate.

Amit Das
  • 1,077
  • 5
  • 17
  • 44

1 Answers1

2

The answer here gives me an idea Check if sequence exists in Postgres (plpgsql), I don't know if this is a perfect solution or not but you can use :

SELECT COUNT(*) 
FROM information_schema.sequences 
WHERE sequence_schema='sch_name' AND sequence_name='sequence_name'

This will give you 0 (if not exist) or 1 (if exist).

So to solve your problem, you have to execute your query in two shots, one to check if your sequence exist, and the second is to select your sequence, so your code should look like this :

String sch_name = "sch_test";
String sequence_name = "sequence_name";

//Check if your sequence exist or not
Query q = createNativeQuery("SELECT COUNT(*) FROM        
                             information_schema.sequences 
                             WHERE sequence_schema='" + sch_name + "' 
                             AND sequence_name='" + sequence_name + "'");

int i = (Integer) q.getSingleResult();
int sequence = 0;

//if the sequence exit it will return 1
if(i == 1){
  //increment your sequence and return the result
  q = createNativeQuery("SELECT nextval('" + sequence_name + "')");
  sequence = (Integer) q.getSingleResult();
}else{
   //sequence not exist
}
Community
  • 1
  • 1
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • The second query will still throw an error if the sequence does not exist: http://rextester.com/ESJW42101 –  Mar 31 '17 at 11:05
  • oops this is correct @a_horse_with_no_name i will try to fix it thank you – Youcef LAIDANI Mar 31 '17 at 11:07
  • @a_horse_with_no_name i really can't arrive to a solution i already use `CASE WHEN` but this not solve the problem i think the better solution is to make with code no? – Youcef LAIDANI Mar 31 '17 at 11:45