Search code examples
oracle11ggeospatialoracle-spatial

I need only one unique result in Oracle sdo_nn Update sentence ,


I need Only one unique result from tableB.Field to tableA.Field I am using sdo operator sdo_nn, this is the code:

UPDATE table1 t1
SET t1.fieldA = (SELECT T2.fieldB,SDO_NN_DISTANCE(1) distance
FROM table1 T1, table2 T2
WHERE 
(sdo_nn(t1.geometry,t2.geometry,'SDO_NUM_RES=1',1)= 'TRUE')
ORDER BY DIST
)
WHERE EXISTS(
    SELECT 1
      FROM table2 t2
     WHERE sdo_nn(t1.geometry, t2.geometry,'SDO_NUM_RES=1',1)='TRUE'
     AND(t2.cell_name = 'string1' or t2.cell_name = string2')AND t1.fieldA = NULL
     );

In the select sentence of the subquery i get an error because i only use one field(t1.fieldA), but in the sentence i use the operator SDO_NN_DISTANCE(1) and the sql developer count this operator like another field. What is the correct way to write this sentence? I only use sql because i need to insert this code in vba

Thanks!!!


Solution

  • Obviously, you can't (simplified)

    set t1.fieldA = (t2.fieldB, distance)  --> you want to put two values into a single column
    

    Therefore, get fieldB alone from the subquery which uses analytic function (row_number) to "sort" rows by sdo_nn_distance(1) desc; then get the first row's fieldB value.

    Something like this (I hope I set the parenthesis right):

    UPDATE table1 t1
       SET t1.fieldA =
              (SELECT x.fieldB                                 --> only fieldB
                 FROM (SELECT T2.fieldB,                       --> from your subquery
                              SDO_NN_DISTANCE (1) distance,
                              ROW_NUMBER ()
                                 OVER (ORDER BY sdo_nn_distance (1) DESC) rn
                         FROM table1 T1, table2 T2
                        WHERE (sdo_nn (t1.geometry,
                                       t2.geometry,
                                       'SDO_NUM_RES=1',
                                       1) = 'TRUE')) x
                WHERE rn = 1)                                  --> where RN = 1
     WHERE EXISTS
              (SELECT 1
                 FROM table2 t2
                WHERE     sdo_nn (t1.geometry,
                                  t2.geometry,
                                  'SDO_NUM_RES=1',
                                  1) = 'TRUE'
                      AND (   t2.cell_name = 'string1'
                           OR t2.cell_name = 'string2')
                      AND t1.fieldA IS NULL);