0

This is starting to drive me crazy and I cannot find the reason why this ain't working!

The tables have triggers on them so cityID and postcodeID get populated automatically. The purpose of this function is to find a city with the same name and return its ID else add it to the table and return the new ID.

CREATE OR REPLACE FUNCTION resolveCity(cityNameIn IN VARCHAR2)
RETURN NUMBER AS
    cityIDOut NUMBER;
BEGIN
    SELECT cityID
    INTO cityIDOut
    FROM tblCities
    WHERE cityName = cityNameIn;

    IF cityIDOut IS NULL THEN
        -- Add this city to the list
        INSERT INTO tblCities (cityName)
        VALUES (cityNameIn)
        RETURNING cityID INTO cityIDOut;
    END IF;

    RETURN(cityIDOut);
END;
/
2
  • Are the triggers BEFORE insert or AFTER insert? Commented May 24, 2017 at 19:16
  • BEFORE, it populates the primary key from sequence Commented May 24, 2017 at 19:21

1 Answer 1

2

If a SELECT fails in PL/SQL a NO_DATA_FOUND exception is raised. In this case there's no handler in the function so it's raised to an outer handler - and apparently there isn't one, so it gets dropped on the floor and lost.

I suggest that you rewrite your function as:

CREATE OR REPLACE FUNCTION resolveCity(cityNameIn IN VARCHAR2)
RETURN NUMBER AS
    cityIDOut NUMBER;
BEGIN
  BEGIN
    SELECT cityID
      INTO cityIDOut
      FROM tblCities
      WHERE cityName = cityNameIn;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      -- Add this city to the list
      INSERT INTO tblCities (cityName)
        VALUES (cityNameIn)
        RETURNING cityID INTO cityIDOut;
  END;

  RETURN(cityIDOut);
END;

Best of luck.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for the answer, unfortunately this returns me: ORA-14551: cannot perform a DML operation inside a query ORA-06512: at "S.RESOLVECITY", line 13 ORA-01403: no data found
How are you invoking this function?
Could you use MERGE and return the new id?
INSERT INTO tblCustomerAddresses (userID, defaultAddress, addressLine1, addressLine2, addressLine3, cityID, postcodeID, countryCode) VALUES(userIDout, 1, sAddressLine1, sAddressLine2, sAddressLine3, resolveCity(sAddressCity), resolvePostcode(sAddressPostcode), sAddressCountry);
I will trying using the MERGE, just need to look it up - thanks for the suggestion!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.