Search This Blog

Showing posts with label CREATE APP. Show all posts
Showing posts with label CREATE APP. Show all posts

Tuesday, June 24, 2025

How Do I Create a stored procedure for displaying SELECT from a table in a report

 Introduction

Creating a stored procedure to perform a SELECT query from a table and display the results in an Oracle APEX report is a useful technique when you want to centralize complex query logic or return custom result sets. Instead of embedding SQL directly in the report region, you can write a PL/SQL stored procedure that returns a ref cursor. This approach improves code maintainability, separates business logic from the UI, and gives you greater control over how data is retrieved and presented.

In Oracle APEX, you can use a stored procedure with a ref cursor to return data from a table and display it in a report region. This approach is useful when you want to encapsulate complex query logic in the database and reuse it across multiple pages or applications. The procedure returns a result set using a SYS_REFCURSOR, which APEX can then use as the source for a report.

Step 1: Open SQL Workshop
Log in to Oracle APEX and go to SQL Workshop. Click on SQL Commands to create the stored procedure.

Step 2: Create the Stored Procedure
Use SQL to define a procedure that returns a ref cursor. Here is an example that selects data from the EMPLOYEES table:

CREATE OR REPLACE PROCEDURE get_employees (
  p_result OUT SYS_REFCURSOR
)
AS
BEGIN
  OPEN p_result FOR
    SELECT employee_id, first_name, last_name, email, hire_date
    FROM employees
    ORDER BY hire_date DESC;
END;

This procedure defines an OUT parameter p_result that holds the result set. Inside the procedure, the cursor is opened with a SELECT statement from the employees table.

Step 3: Create a Report Region in APEX
Go to your APEX application, open the page where you want the report, and enter Page Designer.

  1. Create a new region.

  2. Set the region type to ReportClassic Report or Interactive Report.

  3. Set the Source Type to PL/SQL Function Returning SQL Query.

Step 4: Use the Stored Procedure in the Report Source
Enter the following code in the Source area:

DECLARE
  l_cursor SYS_REFCURSOR;
BEGIN
  get_employees(l_cursor);
  RETURN l_cursor;
END;

This block calls the stored procedure and returns the ref cursor as the report data source.

Step 5: Run and Test the Page
Click Run. Your report should display the data returned by the stored procedure. If the procedure is valid and the table has data, the results will be shown in the report region.

Optional Step: Add Parameters
You can modify the procedure to accept parameters for filtering. For example:

CREATE OR REPLACE PROCEDURE get_employees_by_dept (
  p_dept_id IN NUMBER,
  p_result OUT SYS_REFCURSOR
)
AS
BEGIN
  OPEN p_result FOR
    SELECT employee_id, first_name, last_name, email
    FROM employees
    WHERE department_id = p_dept_id;
END;

Then in APEX, you can pass a page item like this:

DECLARE
  l_cursor SYS_REFCURSOR;
BEGIN
  get_employees_by_dept(:P1_DEPT_ID, l_cursor);
  RETURN l_cursor;
END;

Best Practices
Use clear and meaningful names for procedures and parameters.
Add exception handling if needed.
Keep the SELECT statement optimized for performance.
Use bind variables instead of hardcoding values.
Recompile procedures if you change table structures or logic.

Using a stored procedure with a ref cursor to display data in a report allows you to keep SQL logic in the database, improve reusability, and simplify maintenance across your Oracle APEX application.

Conclusion

Using a stored procedure to return data for a report allows you to organize and reuse query logic while keeping your APEX pages cleaner and more modular. It is especially helpful for complex data retrieval or when the same logic needs to be used across multiple reports. By leveraging ref cursors and PL/SQL procedures, you create a more flexible and scalable foundation for your Oracle APEX applications.

How Do I Create a stored procedure for UPDATING a table

 Introduction

Creating a stored procedure for updating a table in Oracle APEX is a smart way to centralize and manage your data modification logic. Instead of writing repetitive SQL update statements across multiple pages or processes, a stored procedure allows you to write the logic once and call it wherever needed. This improves maintainability, security, and consistency throughout your application, especially when updating rows based on parameters passed from the user interface.


How Do I Create a Stored Procedure for Updating a Table in Oracle APEX
Font: Arial | Format: Plain Text

Creating a stored procedure to update a table in Oracle APEX allows you to encapsulate the update logic in one place, making your application easier to manage and reuse. You can call this procedure from forms, buttons, or processes inside your APEX app.

Step 1: Open SQL Workshop
Log in to Oracle APEX. From the main menu, go to SQL Workshop and click on SQL Commands.

Step 2: Write the Stored Procedure Code
Use the CREATE OR REPLACE PROCEDURE statement to define the logic. Below is an example that updates an employee’s email address based on their employee ID.

CREATE OR REPLACE PROCEDURE update_employee_email (
  p_employee_id IN NUMBER,
  p_new_email   IN VARCHAR2
)
AS
BEGIN
  UPDATE employees
  SET email = p_new_email
  WHERE employee_id = p_employee_id;
END;

In this example:

  • The procedure is named update_employee_email.

  • It accepts two input parameters: p_employee_id and p_new_email.

  • It performs an UPDATE operation on the employees table.

Step 3: Execute the Procedure Code
Click the Run or Execute button to compile the procedure. If there are no errors, the procedure will be created and stored in your schema.

Step 4: Test the Procedure
You can test the procedure by running an anonymous PL/SQL block like this:

BEGIN
  update_employee_email(101, 'newemail@example.com');
END;

This will update the email of the employee with ID 101.

Step 5: Call the Procedure from Your APEX App
In Page Designer, create a button or process that submits data. Under the processing section, add a PL/SQL process with code like this:

BEGIN
  update_employee_email(:P1_EMPLOYEE_ID, :P1_EMAIL);
END;

Make sure that P1_EMPLOYEE_ID and P1_EMAIL are page items that hold the input values.

Step 6: Add Validations if Needed
You can add validations to check if the email is in the correct format or if the employee ID exists before calling the procedure.

Best Practices
Use clear parameter names.
Add error handling using EXCEPTION blocks.
Keep the procedure logic simple and focused.
Grant EXECUTE permission if the procedure needs to be accessed from another schema.

Creating a stored procedure for updating a table helps you manage business logic in one place, improves security, and reduces repeated code across your APEX application. It makes your updates cleaner, safer, and easier to maintain.

Conclusion

Using a stored procedure to update a table simplifies your Oracle APEX application by encapsulating the update logic in a reusable and secure way. It ensures that updates follow a consistent process and allows for easier future changes without touching multiple pages. By calling the procedure from page processes, buttons, or dynamic actions, you maintain clean code separation and gain better control over how and when your data is modified.

Example:

CREATE OR REPLACE PROCEDURE UPDATE customer (   

p_name IN CUSTOMER.NAME%TYPE,  

p_gender IN CUSTOMER.GENDER%TYPE,  

p_address IN CUSTOMER.ADDRESS%TYPE)  

IS  

BEGIN  

UPDATE CUSTOMER SET NAME=p_name, GENDER=p_gender, ADDRESS=p_address WHERE NAME=p_name;  

COMMIT;  

END;  



How Do I Use SQL code for creating and using Stored Procedures

 Introduction

Using SQL code to create and manage stored procedures is an essential part of developing efficient and organized applications in Oracle APEX. Stored procedures allow you to encapsulate SQL and PL/SQL logic into reusable blocks that can be called from different parts of your application, such as buttons, processes, or dynamic actions. This helps improve performance, maintainability, and code reusability by centralizing business logic within the database.

In Oracle APEX, stored procedures are blocks of PL/SQL code stored in the database that can be called repeatedly to perform tasks such as inserting data, validating input, or processing business rules. Creating and using stored procedures helps keep your application logic organized, reusable, and easier to maintain.

Step 1: Open SQL Workshop
Log in to Oracle APEX and go to the main menu. Click on SQL Workshop, then select SQL Commands or Object Browser to create and manage stored procedures.

Step 2: Write SQL Code to Create a Stored Procedure
You can use the CREATE OR REPLACE PROCEDURE statement to define a stored procedure. Below is an example of a simple procedure that inserts a record into a table called employees.

CREATE OR REPLACE PROCEDURE add_employee (
  p_first_name   IN VARCHAR2,
  p_last_name    IN VARCHAR2,
  p_email        IN VARCHAR2
)
AS
BEGIN
  INSERT INTO employees (first_name, last_name, email)
  VALUES (p_first_name, p_last_name, p_email);
END;

Explanation:

  • The procedure is named add_employee.

  • It accepts three input parameters: p_first_name, p_last_name, and p_email.

  • The BEGIN...END block contains the SQL logic to insert a new row into the employees table.

Step 3: Execute the SQL Code
Click the Run or Execute button in SQL Commands. If the syntax is correct and you have privileges, the procedure will be created in your schema.

Step 4: View and Manage Stored Procedures
To view your stored procedure:

  1. Go to SQL Workshop

  2. Click on Object Browser

  3. Under Procedures, find and click on your procedure name
    You can see the source code, compile status, and edit or drop the procedure from here.

Step 5: Call the Stored Procedure from APEX
You can call the stored procedure from APEX using PL/SQL processes, page buttons, or dynamic actions.

Example: Add a button to a form page that calls the procedure on submit. In the button’s process, write:

BEGIN
  add_employee(:P1_FIRST_NAME, :P1_LAST_NAME, :P1_EMAIL);
END;

This will pass values from page items to the stored procedure and execute it.

Best Practices

  • Use clear naming conventions for procedures and parameters.

  • Include exception handling inside your procedure using EXCEPTION WHEN OTHERS THEN.

  • Keep your business logic in the procedure to make it reusable across different pages.

  • Recompile procedures if you make changes to referenced objects.

  • Grant appropriate execution privileges if used across schemas.

Using SQL code to create and use stored procedures in Oracle APEX gives you strong control over your business logic and data processes, allowing you to build robust and maintainable applications.

Conclusion

Creating and using stored procedures with SQL code allows Oracle APEX developers to separate business logic from the user interface, resulting in cleaner, more modular applications. Whether you're performing complex calculations, managing transactions, or automating processes, stored procedures offer a powerful way to control how your application interacts with the database. Mastering stored procedure creation is a key skill for building scalable and maintainable APEX solutions.

How Do I Use SQL code for creating a table

 Introduction

Creating a table using SQL is one of the foundational skills in working with databases and is especially useful when developing applications in Oracle APEX. A table is a structured object that stores data in rows and columns, and writing SQL code to create one gives you full control over its structure. Whether you’re designing a form, building a report, or storing user input, understanding how to write the CREATE TABLE statement is essential for efficient database development.

How Do I Use SQL Code for Creating a Table in Oracle APEX

Font: Arial | Format: Plain Text

Creating a table using SQL code in Oracle APEX is a basic but important task for defining the structure of your application's data. Tables are used to store records in rows and columns, and each column is defined with a specific data type and optional constraints. You use the CREATE TABLE SQL statement to define a new table in the Oracle database that your APEX application will use.

Step 1: Open SQL Workshop
Log in to Oracle APEX. From the App Builder home screen, go to the main menu and click on SQL Workshop. From there, choose SQL Commands to open the SQL editor.

Step 2: Write the CREATE TABLE Statement
In the SQL Commands editor, type the SQL code to create your table. Here is a simple example:

CREATE TABLE employees (
  employee_id   NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  first_name    VARCHAR2(50),
  last_name     VARCHAR2(50),
  email         VARCHAR2(100) UNIQUE,
  hire_date     DATE,
  status        VARCHAR2(20) DEFAULT 'Active'
);

Explanation of the code:

  • employee_id is a unique identifier with an auto-incrementing number.

  • first_name, last_name, and email are text fields with specified length.

  • email is marked as UNIQUE to prevent duplicates.

  • hire_date is a date column to store when the employee was hired.

  • status has a default value of 'Active'.

Step 3: Execute the SQL Code
After writing the SQL command, click the Run or Execute button. If the syntax is correct and you have the necessary privileges, the table will be created in your schema.

Step 4: Verify the Table
To confirm the table has been created:

  1. In SQL Workshop, go to Object Browser.

  2. Find your table under the Tables section.

  3. Click on it to view its structure, columns, and data.

Step 5: Use the Table in Your APEX App
Now that the table exists, you can:

  • Create a form or report on the table using the APEX Page Designer.

  • Insert data using SQL Commands or through APEX forms.

  • Write additional SQL queries to select, update, or delete records.

Best Practices

  • Always name your columns clearly and consistently.

  • Use appropriate data types and sizes for each column.

  • Apply primary keys and constraints to maintain data integrity.

  • Avoid using reserved words as table or column names.

  • Use comments in your SQL to document the purpose of each column when needed.

Using SQL code to create tables gives you full control over your database design and allows you to build a strong foundation for your Oracle APEX application.

Conclusion

Using SQL code to create tables allows developers to define exactly how data will be stored, accessed, and related within an Oracle APEX application. By mastering the CREATE TABLE syntax, including data types, constraints, and keys, you can ensure your application's data layer is well-structured and optimized for performance. This knowledge forms the backbone of building scalable, flexible, and professional-grade APEX applications.



How Do I Get the ID from a dropdown list

 Getting the ID from a Dropdown List in Oracle APEX

Dropdown lists (Select Lists) in Oracle APEX are commonly used to allow users to choose from a predefined set of values. Often, each option in the dropdown represents a display value (e.g., a name) and a corresponding ID (e.g., a unique identifier from a database). Retrieving the selected ID is useful for filtering data, setting values dynamically, or passing it to processes.

This tutorial covers multiple methods for retrieving the ID from a dropdown list using SQL, PL/SQL, JavaScript, and Dynamic Actions.


Setting Up the Dropdown List with an ID and Display Value

Before retrieving the ID, you need to create a Select List that stores both the display name and the corresponding ID.

Step 1: Creating the Dropdown (Select List)

  • Open Page Designer in Oracle APEX.

  • Click CreateItem.

  • Select Select List as the item type.

  • Set the Name to P1_CUSTOMER.

Step 2: Define the List of Values (LOV) Query

A Select List in APEX typically stores two values:

  1. A display value (e.g., customer_name)

  2. A return value (e.g., customer_id)

Example SQL query for retrieving customer data:

SELECT customer_name, customer_id 

FROM customers 

ORDER BY customer_name;

  • The first column (customer_name) is displayed in the dropdown.

  • The second column (customer_id) is stored when an option is selected.

  • Save and run the page. Now, selecting a customer will store their customer_id in P1_CUSTOMER.


Retrieving the Selected ID in PL/SQL

Once a user selects an option, you can retrieve its corresponding ID in PL/SQL.

Example 1: Display the Selected ID Using a PL/SQL Process

  • Create a PL/SQL Process under Processing in Page Designer.

  • Add the following PL/SQL code:

DECLARE 

    v_customer_id NUMBER;

BEGIN

    v_customer_id := :P1_CUSTOMER;

    APEX_DEBUG.INFO('Selected Customer ID: ' || v_customer_id);

END;

  • This code retrieves the selected customer_id and logs it for debugging.

Example 2: Use the ID in a Query to Fetch More Data

If you need to get additional details based on the selected ID, use:

SELECT customer_email, customer_phone 

FROM customers 

WHERE customer_id = :P1_CUSTOMER;

  • This query fetches details of the selected customer.

  • You can assign the values to other page items using Dynamic Actions.


Retrieving the Selected ID Using JavaScript

If you need to retrieve the ID dynamically without submitting the page, you can use JavaScript.

Example 1: Get the ID Using JavaScript

To capture the selected ID in JavaScript, add this script to the Execute JavaScript Code action:

var selectedID = $v("P1_CUSTOMER");  

console.log("Selected Customer ID: " + selectedID);

  • This retrieves the selected value (customer_id) and prints it to the browser console.

Example 2: Store the ID in Another Page Item Using JavaScript

If you need to store the ID in another field dynamically:

$s("P1_SELECTED_CUSTOMER_ID", $v("P1_CUSTOMER"));

  • This sets the value of P1_SELECTED_CUSTOMER_ID to the selected customer_id.


Using Dynamic Actions to Retrieve the ID

Dynamic Actions allow you to retrieve the selected ID without writing custom JavaScript.

Step 1: Create a New Dynamic Action

  • Go to Page DesignerDynamic Actions.

  • Click CreateEventChange.

  • Set Selection Type to Item.

  • Choose P1_CUSTOMER as the affected item.

Step 2: Add an Action to Set a Page Item

  • Click Create ActionSet Value.

  • Set Set Type to Item(s).

  • In Affected Elements, select P1_SELECTED_CUSTOMER_ID.

  • Under Set Value, choose SQL Query and enter:

SELECT customer_id FROM customers WHERE customer_id = :P1_CUSTOMER;

  • This assigns the selected ID to P1_SELECTED_CUSTOMER_ID dynamically.

  • Save and run the page. The ID updates in real time when a new option is selected.


Best Use Cases for Retrieving the Dropdown ID

  • Filtering Reports: Use the selected ID to dynamically filter an Interactive Report or Classic Report.

  • Updating Another Field: Populate text fields, emails, or addresses based on the selected value.

  • Passing Data to PL/SQL: Use the ID in page processes, validations, or calculations.

  • AJAX-Based Updates: Retrieve additional details without a full page reload.


Retrieving the selected ID from a dropdown list in Oracle APEX is essential for interactive applications.

  • PL/SQL is useful for backend processing and queries.

  • JavaScript enables real-time updates without reloading the page.

  • Dynamic Actions provide a no-code approach for setting values based on selections.

By combining these methods, you can create efficient and user-friendly applications that dynamically respond to user input.



EXAMPLE:

Assuming that we have a table like the following:

A screenshot of a computer

AI-generated content may be incorrect.

Where Table TEST_A has the following data

A screenshot of a computer

AI-generated content may be incorrect.

And that we have a dropdown box 

Displaying the text of ValueA1

With a value of “ID” from the table

A close-up of a computer screen

AI-generated content may be incorrect.

What we want to do is save the value from the dropdown list into a text box when we select the value.

A screenshot of a phone

AI-generated content may be incorrect.




Step 1 – Add a “Select List” to the application

A screenshot of a computer

AI-generated content may be incorrect.

Step 2 – Give it a descriptive name and be sure that you select “Select List”

A black box with white text

AI-generated content may be incorrect.

In the List of Values area, add the following:

A screenshot of a computer

AI-generated content may be incorrect.

Your code should look something like this:

select TEST_A.VALUEA1 as VALUEA1,

    TEST_A.ID as ID 

 from TEST_A TEST_A

**** Notice that the placement of the first column will be assigned to the displayed “text” and the second column to the “value”.

Step 3 – Add a dynamic action to the list.

A black screen with white text

AI-generated content may be incorrect.

Step 4 – Add (or use if already created) a TRUE branch and enter the following

A screenshot of a black screen

Description automatically generated

A screenshot of a computer

Description automatically generated

A screenshot of a computer

AI-generated content may be incorrect.

Your code should look like this:

var DisplayValueVar =$("#P44_TESTA_DROPDOWN option:selected").val();

console.log(DisplayValueVar);

apex.item('P44_TESTA_ID_VALUE').setValue(DisplayValueVar);


var DisplayValueVar  - Save into this declared variable named DisplayValueVar 

The value of the P44_TESTA_DROPDOWN control

$("#P44_TESTA_DROPDOWN option:selected").val();

The $(“CoNTROL_NAME”) identifies what control you want to get values from

The option:selected is what identifies what you selected from the control.

.val(); gets the value

If you wanted to get the text from the list you would use .text();

Saves to the browser javascript console:

console.log(DisplayValueVar);


Saves the value from the variable into the TEXT BOX  'P44_TESTA_ID_VALUE’

apex.item('P44_TESTA_ID_VALUE').setValue(DisplayValueVar); 


Step 5 – Add a second true branch

A screenshot of a computer

AI-generated content may be incorrect.


Set the following values

A screenshot of a computer program

Description automatically generated


The following javascript code saves the values into the APEX SESSION for further use in the app.

APEX_UTIL.SET_SESSION_STATE('P44_TESTA_ID_VALUE',v('P44_TESTA_ID_VALUE'));


Final product should look something like this next image where the selected data value is selected and the id of that value is displayed in the textbox below upon selection.

A blue and white line

Description automatically generated