Your code assumes that there are always the same number of records in both tables T1 and T2 (I call them that because you have not said their names). In case there is a row in the first table that does not exist in the second because your code will stop working because the second ResultSet rs2
will have advanced one position. This can be seen better in the following example:
rs1: [ 1, 2, 3, 4, 5 ]
rs2: [ 1, 2, 4, 5]
According to your code, rs1
in its first position must have the same value as rs2
in its first position. For the example, this is correct. The same thing happens in the second position. In the third position, the values are different so the cursor of rs2
should be kept in the same position but according to your algorithm rs2
will still advance generating data inconsistency.
You can solve this at the application level, but it is very expensive:
You run two queries, perhaps with a lot of data.
You are uploading this data to travel through the network.
You are always going to insert in table T3. Each operation INSERT
means more access to the database.
When you have to perform functions that access the network, for example operations against the database, you should minimize the calls made, thus optimizing the speed of your application (for a long time, even if it does not appear at the beginning). This problem can be solved with a single script, in the following way:
INSERT INTO T3 (col1, col2, col3, col4, col5)
SELECT
T2.col1,
T2.col2,
T2.col3,
Nz(T1.col4, 'sin datos'),
Nz(T1.col5, 'sin datos)
FROM T2 LEFT JOIN T1 ON T1.col1 = T2.col1
AND T1.col2 = T2.col2
AND T1.col3 = T2.col3
Explanation of the query:
-
INSERT INTO T3 (col1, col2, col3, col4, col5) SELECT
: you indicate that all the results of the query obtained in the SELECT
statement will be inserted. Indicate the columns of table T3 where the data will be inserted (place the real names of the columns).
-
Nz(T1.col4, 'sin datos')
: Nz
is a SQL function that receives two parameters, the value to evaluate and the default value. If the value to be evaluated (first parameter) is null, then the default value (second parameter) is returned. As you explain, you must use the T2 data to insert, otherwise you must register 'sin datos'
.
-
FROM T2 LEFT JOIN T1 ON ...
: A LEFT JOIN
allows you to make a union of the table on the left with the table on the right, always returning all the results of the left table even though there is no equality with the right table. For those records where there was no equality, the results of the right table return NULL
, therefore the use of Nz
when obtaining the data.
After putting together this query, your Java code is reduced to the execution of 1 single query, reducing network access and optimizing the use of the database.