Search code examples
sqloracle-databaseora-01427

How to match the longest string and update the value?


I need to compare and match the longest match of two strings in two different tables and update one values if there is a closest match.

Table 1     Table 2
stack1     stack2
ABCDEFG    ABC
GHIJKLM    ABCDE
PQRSUVW    ABCDEF

I need to compare these two tables and match the closeet one and update Table 1 first row as ABCDEF the closest match, Please can anyone help me out. I am stuck here.

Here is my query

UPDATE table1 A 
   SET A.stack1 = (SELECT DISTINCT B.stack2 
                     FROM table2 B 
                    WHERE A.stack1 LIKE CONCAT(B.stack2,'%')) 
 WHERE name = 'name';

with this query am getting an error called

ORA-01427: single-row subquery returns more than one row


Solution

  • You need to make the subquery return only a single match (the longest one). In your case MAX should do that.

    UPDATE table1 A 
    SET A.stack1 = (SELECT Max( B.stack2 )
                     FROM table2 B 
                    WHERE A.stack1 LIKE CONCAT(B.stack2,'%')) 
    WHERE name = 'name';
    

    Also, you should think about the case where nothing matches.