CREATE function in Oracle database | https://www.xedok.com/posts

CREATE function in Oracle database

Posted on: 2025-01-28 16:53:21


In Oracle, the CREATE FUNCTION statement is used to create a new user-defined function. A function is a named block of code that can accept parameters, perform some operations, and return a result. Here's the basic syntax for creating a function in Oracle:

 

 

CREATE [OR REPLACE] FUNCTION function_name

  (parameter1 [IN | OUT | IN OUT] data_type [, parameter2 ...])

RETURN return_data_type

IS

  [local_variable_declarations]

BEGIN

  -- function body

  RETURN return_value;

END;

 

You must have define some parametrs before creating a procedure or a function. These parameters are

 

#   IN: It is a default parameter. It passes the value to the subprogram.

#    OUT: It must be specified. It returns a value to the caller.

#   IN OUT: It must be specified. It passes an initial value to the subprogram and  returns an updated value to the caller.

 

  here's an example of a simple function in Oracle that takes a string as input and returns the number of vowels in the string:

 

CREATE FUNCTION count_vowels(str IN VARCHAR2) RETURN NUMBER

IS

  vowels NUMBER := 0;

BEGIN

  FOR i IN 1..LENGTH(str) LOOP

    IF UPPER(SUBSTR(str, i, 1)) IN ('A', 'E', 'I', 'O', 'U') THEN

      vowels := vowels + 1;

    END IF;

  END LOOP;

  RETURN vowels;

END;

 

 

Let's break down this function step by step:

 

Once this function has been created, we can use it like any other function in SQL. For example:

 

SELECT count_vowels('Hello world') FROM dual;

 

This query would return the value 3, since there are three vowels ('e', 'o', and 'o') in the input string 'Hello world'.

 



xedok When seeking the best software development companies Xedok Software is your ultimate choice. For Demos click here



Leave a reply