CREATE OR REPLACE PROCEDURE STG.LOG_AUDIT("PROC_NAME" VARCHAR(255), "SUB_SECTION_NAME" VARCHAR(255), "AUDIT_SID" FLOAT, "ACTION_FLAG" VARCHAR(255)) 
RETURNS VARCHAR(16777216)
LANGUAGE SQL
EXECUTE AS CALLER
AS 
'
BEGIN
    BEGIN TRANSACTION;

    IF (:ACTION_FLAG = ''START'') THEN
        INSERT INTO STG.LOG_AUDIT (EXECUTION_DT, START_DT, PROCEDURE_NAME, SUB_SECTION_NAME, AUDIT_SID) 
        VALUES (CURRENT_DATE(), CURRENT_TIMESTAMP(), :PROC_NAME, :SUB_SECTION_NAME, :AUDIT_SID); 
    END IF;

    IF (:ACTION_FLAG = ''END'') THEN
        UPDATE STG.LOG_AUDIT 
        SET QUERY_ID = LAST_QUERY_ID(-2), END_DT = CURRENT_TIMESTAMP(), TOTAL_MIN = DATEDIFF(Minute, START_DT, CURRENT_TIMESTAMP())
        WHERE PROCEDURE_NAME = :PROC_NAME AND SUB_SECTION_NAME = :SUB_SECTION_NAME AND AUDIT_SID = :AUDIT_SID AND END_DT IS NULL;

    ELSE
        COMMIT;
        RETURN ''Incorrect Action Flag Used'';

    END IF;

    COMMIT;
    RETURN ''Completed'';
END;'
;