Creating Dynamic Data Tables in PL/SQL using json and HTML

To retrieve data in JSON format using an Oracle SQL query, you can use the JSON_OBJECT, JSON_ARRAYAGG, and JSON_TABLE functions. Here’s an example query:

SELECT JSON_OBJECT(
           'id'          VALUE emp.employee_id,
           'first_name'  VALUE emp.first_name,
           'last_name'   VALUE emp.last_name,
           'hire_date'   VALUE emp.hire_date,
           'salary'      VALUE emp.salary
       ) AS emp_json
FROM   employees emp

This query selects data from the employees table and returns it as a JSON object with the specified keys and values.

To create a dynamic data table in PL/SQL using HTML, CSS, and JavaScript, you can use the HTP and HTF packages to generate HTML markup, and then use JavaScript to manipulate the table data dynamically.

Here’s an example PL/SQL code snippet that creates a simple data table using HTML and CSS:

DECLARE
   l_emp_data   VARCHAR2 (32767);
BEGIN
   SELECT JSON_ARRAYAGG (emp_json)
     INTO l_emp_data
     FROM (
             SELECT JSON_OBJECT(
                        'id'          VALUE emp.employee_id,
                        'first_name'  VALUE emp.first_name,
                        'last_name'   VALUE emp.last_name,
                        'hire_date'   VALUE emp.hire_date,
                        'salary'      VALUE emp.salary
                    ) AS emp_json
               FROM   employees emp
          );

   HTP.p ('<table>');
   HTP.p ('<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Hire Date</th><th>Salary</th></tr>');

   FOR i IN (SELECT * FROM JSON_TABLE(l_emp_data, '$[*]' COLUMNS (id NUMBER PATH '$.id', first_name VARCHAR2(50) PATH '$.first_name', last_name VARCHAR2(50) PATH '$.last_name', hire_date DATE PATH '$.hire_date', salary NUMBER PATH '$.salary'))) LOOP
      HTP.p ('<tr>');
      HTP.p ('<td>' || i.id || '</td><td>' || i.first_name || '</td><td>' || i.last_name || '</td><td>' || i.hire_date || '</td><td>' || i.salary || '</td>');
      HTP.p ('</tr>');
   END LOOP;

   HTP.p ('</table>');
END;

This code snippet retrieves the JSON data using the query above, converts it to a PL/SQL string using JSON_ARRAYAGG, and then uses JSON_TABLE to parse the JSON data into columns.

It then generates HTML markup for a data table using the HTP package, and loops through the data using a FOR loop to generate HTML markup for each row in the table. Finally, it outputs the HTML markup using HTP.p.

Leave a Reply

Your email address will not be published. Required fields are marked *