why do i get the error message when i transferred the insert method to the function?

Oracle does not support the SQL Server syntax INSERT ... ON DUPLICATE KEY UPDATE .... Use a MERGE statement instead.

FUNCTION ADD_TOKEN(
  p_userID IN user_notifications_token.userID%TYPE,
  p_token  IN user_notifications_token.token%TYPE,
  p_type   IN user_notifications_token.type%TYPE
) RETURN SYS_REFCURSOR
IS 
  rc  SYS_REFCURSOR;
BEGIN
  MERGE INTO user_notifications_token dst
  USING (
    SELECT p_userID AS userID,
           p_token AS token,
           p_type AS type
    FROM   DUAL
  ) src
  ON ( src.userId = dst.userID )
  WHEN MATCHED THEN
    UPDATE SET token = src.token, type = src.type
  WHEN NOT MATCHED THEN
    INSERT ( userId, token, type ) VALUES ( src.userId, src.token, src.type );

  -- Do stuff
  
  RETURN rc;
END ADD_TOKEN;

Then if you do:

DECLARE
  rc SYS_REFCURSOR;
BEGIN
  rc := package_name.ADD_TOKEN( 1, 'ABC', 'A' );
  rc := package_name.ADD_TOKEN( 1, 'DEF', 'D' );
END;
/

The table will contain:

USERID | TOKEN | TYPE
-----: | :---- | :---
     1 | DEF   | D   

db<>fiddle here

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top