0

I am trying to use ResultSetMetaData to frame a SQL query for checking if there are duplicate records in a table dynamically.

The query for checking duplicate records will look like this

select 
col1,
col2,
col3
from Table A
group by 
col1,
col2,
col3
having count(*)>1

Most of this code is boilerplate and i can extract all the columns of the table using ResultSetMetaData. But I am not sure how to do this in an elegant way and handle the last missing comma.

Santhiya
  • 99
  • 2
  • 3
  • 7

1 Answers1

0

I tend to use Joiner from the Guava Libraries in these kind of situation. With joiner you could write something like

String.format(
  "select %1$s from table %s group by %1$s having count(*) > 1",
  "tablename",
  Joiner.on(",").join("col1","col2","col3")
);

If you are using Java 8 then you can use String.join instead.

Please do check that the tablenames are properly quoted if necessary.

Aleksi Yrttiaho
  • 8,266
  • 29
  • 36