Wednesday, November 4, 2020

Variables in UNIX

 [scott]$ cat sample.sh
#!/bin/bash
#This is basic bash script exmaple.
a=Hello
b='Hello'
c="Hello"
d=123
echo $a
echo $b
echo $c
echo $d
echo "Hello, value of d is $d"
[scott]$ sh sample.sh
Hello
Hello
Hello
123
Hello, value of d is 123
[scott]$
Variables Declaration
[scott]$ cat sample.sh
#!/bin/bash
#This is basic bash script exmaple.
a=Hello
b='Hello'
c="Hello"
d=123
echo $a
echo $b
echo $c
echo $d
echo "Hello, value of d is $d"
echo
echo
declare -i e=123 #e is an integer
declare -r f=999 #f is read-only
declare -l g="king kong" #g is in lower case
declare -u h="Hello World" #h is in upper case
echo $e
echo $f
echo $g
echo $h
[scott]$ sh sample.sh
Hello
Hello
Hello
123
Hello, value of d is 123

123
999
king kong
HELLO WORLD
[scott]$
Built-in Variables
[scott]$ echo $HOME
/u02/test/abc
[scott]$ echo $PWD
/u04/ftp/scott
[scott]$ echo $MACHTYPE
x86_64-redhat-linux-gnu
[scott]$ echo $HOSTNAME
abc12345667890
[scott]$ echo $BASH_VERSION
4.1.2(2)-release
[scott]$ echo $SECONDS
8010
[scott]$ echo $0
-bash
[scott]$

echo in UNIX

 [scott]$ vi sample.sh
[scott]$ cat sample.sh
#!/bin/bash
#This is basic bash script exmaple.
name="Raj"
echo Hello $name, country\(ind\)!
echo 'Hello $name, country(IND)!'
echo "Hello $name,country(IND)!"
[scott]$ sh sample.sh
Hello Raj, country(ind)!
Hello $name, country(IND)!
Hello Raj,country(IND)!
[scott]$

Tilde and Brace usage in UNIX

 [test scott]$ pwd
/u04/ftp/orcl/scott
[test scott]$ cd ..
[test orcl]$ echo ~-
/u04/ftp/orcl/scott
[test orcl]$ pwd
/u04/ftp/orcl
[test orcl]$ touch {apple,grape,banana}
[test orcl]$ ls
apple  banana  grape  scott/
[test orcl]$ ls -l
total 2
-rw-rw-r--  1 apps apps  0 Nov  4 06:21 apple
-rw-rw-r--  1 apps apps  0 Nov  4 06:21 banana
-rw-rw-r--  1 apps apps  0 Nov  4 06:21 grape
drwxrwxrwx 13 apps root  14 Nov  3 10:56 scott/
[test orcl]$ touch file_{1..6}
[test orcl]$ ls -l
total 2
-rw-rw-r--  1 apps apps  0 Nov  4 06:21 apple
-rw-rw-r--  1 apps apps  0 Nov  4 06:21 banana
-rw-rw-r--  1 apps apps  0 Nov  4 06:22 file_1
-rw-rw-r--  1 apps apps  0 Nov  4 06:22 file_2
-rw-rw-r--  1 apps apps  0 Nov  4 06:22 file_3
-rw-rw-r--  1 apps apps  0 Nov  4 06:22 file_4
-rw-rw-r--  1 apps apps  0 Nov  4 06:22 file_5
-rw-rw-r--  1 apps apps  0 Nov  4 06:22 file_6
-rw-rw-r--  1 apps apps  0 Nov  4 06:21 grape
drwxrwxrwx 13 apps root  14 Nov  3 10:56 scott/
[test orcl]$ ls -l
total 2
drwxrwxrwx 13 apps root 14 Nov  3 10:56 scott/
[test orcl]$ ls -l
total 2
drwxrwxrwx 13 apps root 14 Nov  3 10:56 scott/
[test orcl]$ ls
scott/
[test orcl]$ pwd
/u04/ftp/orcl
You have mail in /var/spool/mail/apps
[test orcl]$ cd scott
[test scott]$
[test scott]$
[test scott]$ clear
[test scott]$ pwd
/u04/ftp/orcl/scott
[test scott]$ cd ..
[test orcl]$ echo ~-
/u04/ftp/orcl/scott
[test orcl]$ pwd
/u04/ftp/orcl
[test orcl]$ ls
scott/
[test orcl]$ ls -l
total 2
drwxrwxrwx 13 apps root 14 Nov  3 10:56 scott/
[test orcl]$ touch {apple banana cherry}
[test orcl]$ ls -l
total 2
-rw-rw-r--  1 apps apps  0 Nov  4 06:31 {apple
-rw-rw-r--  1 apps apps  0 Nov  4 06:31 banana
-rw-rw-r--  1 apps apps  0 Nov  4 06:31 cherry}
drwxrwxrwx 13 apps root  14 Nov  3 10:56 scott/
[test orcl]$ toych file_{1..5}
-bash: toych: command not found
[test orcl]$ ls -l
total 2
-rw-rw-r--  1 apps apps  0 Nov  4 06:31 {apple
-rw-rw-r--  1 apps apps  0 Nov  4 06:31 banana
-rw-rw-r--  1 apps apps  0 Nov  4 06:31 cherry}
drwxrwxrwx 13 apps root  14 Nov  3 10:56 scott/
[test orcl]$ echo {1..10..2}
1 3 5 7 9
[test orcl]$ echo {1..10..3}
1 4 7 10
[test orcl]$ echo {A..Z}
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
[test orcl]$ echo {a..z}
a b c d e f g h i j k l m n o p q r s t u v w x y z
[test orcl]$ echo {0..9}
0 1 2 3 4 5 6 7 8 9
[test orcl]$ echo {0..21}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
[test orcl]$ echo {a..Z}
a ` _ ^ ]  [ Z
[test orcl]$ echo {m..a..2}
m k i g e c a
[test orcl]$ touch {apple,banana}_{0..2}{a..b}
You have mail in /var/spool/mail/apps
[test orcl]$ ls
apple_0a  apple_0b  apple_1a  apple_1b  apple_2a  apple_2b  banana_0a  banana_0b  banana_1a  banana_1b  banana_2a  banana_2b  scott/
[test orcl]$

Tuesday, November 3, 2020

copy file names from UNIX server to Oracle Database

1. connect to scott user and create below table

 CREATE TABLE SFTP_FILE_NAMES (FILE_NAME VARCHAR2(100),PROCESSED_ON DATE);

2. assume /u04/ftp/abcdev/abc/scripts/file_list.20201102 contains below files

sftp> cd /test
sftp> ls -l 20201102*
-rwx------    0 0        0          112255 Nov  2 01:04 20201102_orcl_result1.xml
-rwx------    0 0        0          112255 Nov  2 05:09 20201102_orcl_result2.xml
-rwx------    0 0        0          181669 Nov  2 09:03 20201102_orcl_result3.xml
-rwx------    0 0        0          166850 Nov  2 13:05 20201102_orcl_result4.xml
-rwx------    0 0        0          117372 Nov  2 17:01 20201102_orcl_result5.xml
-rwx------    0 0        0           35570 Nov  2 22:01 20201102_orcl_result50.xml
-rwx------    0 0        0           77009 Nov  2 21:03 20201102_orcl_result6.xml
sftp> 

3. create load_files2db.sh to copy the files from unix to oracle database

#!/bin/bash
export ORACLE_HOME=/u02/test/abc/instantclient/instantclient_11_2
export TNS_ADMIN=/u02/test/abc/instantclient/instantclient_11_2/network/admin
export LD_LIBRARY_PATH=$ORACLE_HOME
export PATH=$PATH:$ORACLE_HOME/bin
DATETIME=`date +%d-%^h-%y`
CTLDIR=/u04/ftp/abcdev/ac/inactive_ctls
LOGDIR=/u04/ftp/abcdev/abc/inactive_logs
BADDIR=/u04/ftp/abcdev/abc/inactive_bads
ctlfile=$CTLDIR/$DATETIME".ctl"
logfile=$LOGDIR/$DATETIME".log"
badfile=$BADDIR/$DATETIME".bad"
FILENAMES=/u04/ftp/abcdev/abc/scripts/file_list.`date -d "1 days ago" -u +%Y%m%d`
echo "LOAD DATA" > $ctlfile
echo "INFILE *" >> $ctlfile
echo "BADFILE '$badfile'" >> $ctlfile
echo "APPEND" >> $ctlfile
echo "INTO TABLE SCOTT.SFTP_FILE_NAMES" >> $ctlfile
echo "FIELDS TERMINATED BY ','" >> $ctlfile
echo "(" >> $ctlfile
echo "FILE_NAME CHAR(100)," >> $ctlfile
echo "PROCESSED_ON DATE" >> $ctlfile
echo ")" >> $ctlfile
echo "BEGINDATA" >> $ctlfile
if [ $(grep -m 1 '\.xml' $FILENAMES|awk '{print $NF}') ];
then
for line in $(grep '\.xml' $FILENAMES|awk '{print $NF}')
do
echo `echo $line|tr -d '\r'`","$DATETIME >> $ctlfile
done
else
echo ""","$DATETIME >> $ctlfile
fi
$ORACLE_HOME/bin/sqlldr control=$ctlfile userid=SCOTT/tiger@ORCL log=$logfile
exit

4. run the script using the command -  ./ load_files2db.sh or sh load_files2db.sh

5. connect to scott user and verify the results 

SELECT * FROM SCOTT.SFTP_FILE_NAMES;

FILE_NAME        PROCESSED_ON
----------------------------------------------------
20201102_orcl_result1.xml 03-NOV-20
20201102_orcl_result2.xml 03-NOV-20
20201102_orcl_result3.xml 03-NOV-20
20201102_orcl_result4.xml 03-NOV-20
20201102_orcl_result5.xml 03-NOV-20
20201102_orcl_result50.xml 03-NOV-20
20201102_orcl_result6.xml 03-NOV-20

Monday, November 2, 2020

echo and read commands in UNIX

 [oracle]$ echo "Hello World"
Hello World
[oracle]$ read
Hi
[oracle]$ echo "Hello";echo "World"
Hello
World
[oracle]$ echo "what is your name?";read name;echo "Hello $name"
what is your name?
Raj
Hello Raj
[oracle]$ echo "what is your name?";read name;echo "Hello $name";echo "Press Enter to continue";read
what is your name?
Raj
Hello Raj
Press Enter to continue
[oracle]$

$ echo "One"
One
$ echo "one" > output.txt
$ cat output.txt
one
$ echo "one" > output.txt
$ cat output.txt
one
$ echo "one" >> output.txt
$ cat output.txt
one
one
$ echo "one" >> output.txt
$ cat output.txt
one
one
one
$

sed command in unix

$ vi sample.txt
$ cat sample.txt
one two three
this is example for sed substitution
$ cat sample.txt|sed 's/t/T/'
one Two three
This is example for sed substitution
$ cat sample.txt|sed 's/t/T/g'
one Two Three
This is example for sed subsTiTuTion
$ sed 's/t/T/g' sample.txt
one Two Three
This is example for sed subsTiTuTion
$ cat sample.txt
one two three
this is example for sed substitution
$ sed -i 's/t/T/g' sample.txt
$ cat sample.txt
one Two Three
This is example for sed subsTiTuTion
$
**************************************************************************
[oracle]$ cat sample.txt
one two three
10 aug 1991
5 may 2020
sed command is used to replace string or characters
[oracle]$ sed 's/[0-9]/*/g' sample.txt
one two three
** aug ****
* may ****
sed command is used to replace string or characters
[oracle]$ sed 's/[0-9][0-9]/*/g' sample.txt
one two three
* aug **
5 may **
sed command is used to replace string or characters
[oracle]$ sed 's/[0-9]/(&)/g' sample.txt
one two three
(1)(0) aug (1)(9)(9)(1)
(5) may (2)(0)(2)(0)
sed command is used to replace string or characters
[oracle]$ sed 's/[a-z]/(&)/g' sample.txt
(o)(n)(e) (t)(w)(o) (t)(h)(r)(e)(e)
10 (a)(u)(g) 1991
5 (m)(a)(y) 2020
(s)(e)(d) (c)(o)(m)(m)(a)(n)(d) (i)(s) (u)(s)(e)(d) (t)(o) (r)(e)(p)(l)(a)(c)(e) (s)(t)(r)(i)(n)(g) (o)(r) (c)(h)(a)(r)(a)(c)(t)(e)(r)(s)
[oracle]$ sed -i  's/t/T/g' sample.txt
[oracle]$ cat sample.txt
one Two Three
10 aug 1991
5 may 2020
sed command is used To replace sTring or characTers
[oracle]$ sed 's/[a-z]/*/g' sample.txt
*** T** T****
10 *** 1991
5 *** 2020
*** ******* ** **** T* ******* *T**** ** ******T***
[oracle]$ sed 's/[A-Z]/*/g' sample.txt
one *wo *hree
10 aug 1991
5 may 2020
sed command is used *o replace s*ring or charac*ers
[oracle]$ sed 's/[A-Za-z]/*/g' sample.txt
*** *** *****
10 *** 1991
5 *** 2020
*** ******* ** **** ** ******* ****** ** **********
[oracle]$ sed 's/[a-Z]/*/g' sample.txt
*** *** *****
10 *** 1991
5 *** 2020
*** ******* ** **** ** ******* ****** ** **********
[oracle]$ sed 's/[0-Z]/*/g' sample.txt
*** *** *****
** *** ****
* *** ****
*** ******* ** **** ** ******* ****** ** **********
You have mail in /var/spool/mail/ougbs
[oracle]$ sed 's/[0-5]/*/g' sample.txt
one Two Three
** aug *99*
* may ****
sed command is used To replace sTring or characTers
[oracle]$ sed 's/[d-m]/*/g' sample.txt
on* Two T*r**
10 au* 1991
5 *ay 2020
s** co**an* *s us** To r*p*ac* sTr*n* or c*aracT*rs
[oracle]$
*********************************************************************

Monday, October 26, 2020

Convert date to UTC TimeZone in Oracle

SELECT SYSDATE,
       SYSTIMESTAMP,
       CURRENT_DATE,
       CURRENT_TIMESTAMP,
       TO_CHAR (SYSTIMESTAMP AT TIME ZONE 'UTC', 'YYYY/MM/DD HH24:MI:SS TZD')
          DT_AS_UTC,
       TO_CHAR (SYSTIMESTAMP AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS')
          DT_AS_UTC,
       TO_CHAR (SYS_EXTRACT_UTC (SYSTIMESTAMP), 'yyyy-mm-dd"T"hh24:mi:ss"Z"')
          DT_AS_UTC
  FROM DUAL;


 

Monday, October 12, 2020

Data Validation in SQL Server

DROP TABLE if exists #temp1,#temp2;


SELECT empno, HASHBYTES ('SHA2_256', CONCAT ([ename]

      ,[hiredate]

      ,[job]

      ,[deptno]

      ,CONVERT(DECIMAL(32,6),[sal])

      )) HashByte

      INTO #temp1

  FROM [prod].[scott].[EMP];


SELECT empno, HASHBYTES ('SHA2_256', CONCAT ([ename]

      ,[hiredate]

      ,[job]

      ,[deptno]

      ,CONVERT(DECIMAL(32,6),[sal])

      )) HashByte

      INTO #temp2

  FROM [stage].[scott].[EMP];



CREATE clustered INDEX IX ON #temp2  (empno);


CREATE clustered INDEX IX1 ON #temp1  (empno);


-- Data Validation


SELECT top 10  *  FROM #temp1 t1

  WHERE  not EXISTS (SELECT 1 FROM #temp2 t2 where t1.empno=t2.empno and t1.HashByte=t2.HashByte )


-- Sample Record


SELECT 'prod'

   [empno] 

      ,[ename]

      ,[hiredate]

      ,[job]

      ,[deptno]

      ,CONVERT(DECIMAL(32,6),[sal])

FROM [prod].[scott].[EMP]

WHERE [empno] = 7863

UNION ALL

SELECT 'stage'

   [empno] 

      ,[ename]

      ,[hiredate]

      ,[job]

      ,[deptno]

      ,CONVERT(DECIMAL(32,6),[sal])

FROM [stage].[scott].[EMP]

WHERE [empno] = 7863;

  

Monday, August 10, 2020

File Upload and insert data to the table in Oracle APEX

CREATE TABLE STUDENT_FILES
(
   FILE_ID        NUMBER,
   FILE_NAME      VARCHAR2 (100),
   FILE_TYPE      VARCHAR2 (500),
   FILE_CONTENT   BLOB,
   IS_PROCESSED   CHAR (1) DEFAULT 'N',
   CONSTRAINT STUDENT_FILES_PK PRIMARY KEY (FILE_ID)
);

CREATE TABLE STUDENT_DETAILS
(
   ID        NUMBER,
   NAME      VARCHAR2 (100),
   ADDRESS   VARCHAR2 (500),
   DOB       DATE,
   GENDER    CHAR (1),
   CONSTRAINT STD_DTLS_PK PRIMARY KEY (ID)
);

CREATE TABLE APP_DEBUG (LOG_DATE DATE,LOG_MSG VARCHAR2(2000));

-- student_details.csv

ID,NAME,ADDRESS,DOB,GENDER

1,SIVA,"#3-85,Gorantla,pin-515231",29-Dec-90,M

2,RAJ,"#3-85,Nidimaidi Village and Post,Gorantla,pin-515110",10-Aug-91,M

3,HARI,"#3/34,Anantapur,pin-515222",1-Jan-91,F

4,JANA,"#3/34,Anantapur,pin-444444",1-Jan-91,


-- View/Download Uploaded files


SELECT FILE_ID,
       FILE_NAME,
       FILE_TYPE,
       DBMS_LOB.GETLENGTH (FILE_CONTENT) AS FILE_CONTENT,
       IS_PROCESSED
  FROM STUDENT_FILES;

-- upload file to the table


DECLARE
   v_file_id   NUMBER;
BEGIN
  SELECT NVL (MAX (file_id), 0) + 1 INTO v_file_id FROM student_files;

   INSERT INTO student_files
      SELECT v_file_id,
             name,
             mime_type,
             blob_content,
             'N'
        FROM apex_application_temp_files
       WHERE name = :P18_FILE_BROWSE;

   DELETE FROM apex_application_temp_files
         WHERE name = :P18_FILE_BROWSE;

   COMMIT;
END;

-- insert file data to the table


DECLARE
   p_id                       NUMBER;
   p_clob                     CLOB;
   p_delim                    VARCHAR2 (100) := ',';
   p_optionally_enclosed      VARCHAR2 (100) := '"';

   --
   CARRIAGE_RETURN   CONSTANT CHAR (1) := CHR (13);
   LINE_FEED         CONSTANT CHAR (1) := CHR (10);
   --
   l_char                     CHAR (1);
   l_lookahead                CHAR (1);
   l_pos                      NUMBER := 0;
   l_token                    VARCHAR2 (32767) := NULL;
   l_token_complete           BOOLEAN := FALSE;
   l_line_complete            BOOLEAN := FALSE;
   l_new_token                BOOLEAN := TRUE;
   l_enclosed                 BOOLEAN := FALSE;
   --
   l_lineno                   NUMBER := 1;
   l_columnno                 NUMBER := 1;

   l_id                       student_details.id%TYPE;
   l_name                     student_details.name%TYPE;
   l_address                  student_details.address%TYPE;
   l_dob                      student_details.dob%TYPE;
   l_gender                   student_details.gender%TYPE;
   l_count                    NUMBER := 0;
   i_flag                     CHAR (1) := NULL;
   v_error                    VARCHAR2 (2000) := NULL;
BEGIN
   SELECT FILE_ID, FILE_CONTENT
     INTO p_id, p_clob
     FROM (  SELECT *
               FROM STUDENT_FILES
              WHERE IS_PROCESSED = 'N'
           ORDER BY FILE_ID ASC)
    WHERE ROWNUM < 2;

   INSERT INTO app_debug
        VALUES (SYSTIMESTAMP, 'File Upload~begin');

   LOOP
      -- increment position index
      l_pos := l_pos + 1;

      BEGIN
         -- get next character from clob
         l_char := DBMS_LOB.SUBSTR (p_clob, 1, l_pos);
      EXCEPTION
         WHEN OTHERS
         THEN
            l_char := '-';
      END;

      -- exit when no more characters to process
      EXIT WHEN l_char IS NULL OR l_pos > DBMS_LOB.getLength (p_clob);

      -- if first character of new token is optionally enclosed character
      -- note that and skip it and get next character
      IF l_new_token AND l_char = p_optionally_enclosed
      THEN
         l_enclosed := TRUE;
         l_pos := l_pos + 1;
         l_char := DBMS_LOB.SUBSTR (p_clob, 1, l_pos);
      END IF;

      l_new_token := FALSE;

      BEGIN
         -- get look ahead character
         l_lookahead := DBMS_LOB.SUBSTR (p_clob, 1, l_pos + 1);
      EXCEPTION
         WHEN OTHERS
         THEN
            l_lookahead := '-';
      END;


      -- dbms_output.put_line('position='||l_pos);
      -- inspect character (and lookahead) to determine what to do
      IF l_char = p_optionally_enclosed AND l_enclosed
      THEN
         IF l_lookahead = p_optionally_enclosed
         THEN
            l_pos := l_pos + 1;
            l_token := l_token || l_lookahead;
         ELSIF l_lookahead = p_delim
         THEN
            l_pos := l_pos + 1;
            l_token_complete := TRUE;
         ELSE
            l_enclosed := FALSE;
         END IF;
      ELSIF l_char IN (CARRIAGE_RETURN, LINE_FEED) AND NOT l_enclosed
      THEN
         l_token_complete := TRUE;
         l_line_complete := TRUE;

         IF l_lookahead IN (CARRIAGE_RETURN, LINE_FEED)
         THEN
            l_pos := l_pos + 1;
         END IF;
      ELSIF l_char = p_delim AND NOT l_enclosed
      THEN
         l_token_complete := TRUE;
      ELSIF l_pos = DBMS_LOB.getLength (p_clob)
      THEN
         l_token := l_token || l_char;
         l_token_complete := TRUE;
         l_line_complete := TRUE;
      ELSE
         l_token := l_token || l_char;
      END IF;

      -- process a new token
      IF l_token_complete
      THEN
         INSERT INTO app_debug
                 VALUES (
                           SYSTIMESTAMP,
                              'File Upload~'
                           || 'R'
                           || l_lineno
                           || 'C'
                           || l_columnno
                           || ': '
                           || NVL (l_token, '**null**'));

         DBMS_OUTPUT.put_line (
               'R'
            || l_lineno
            || 'C'
            || l_columnno
            || ': '
            || NVL (l_token, '**null**'));

         IF l_lineno > 1
         THEN
            CASE l_columnno
               WHEN 1
               THEN
                  l_id := l_token;
               WHEN 2
               THEN
                  l_name := l_token;
               WHEN 3
               THEN
                  l_address := l_token;
               WHEN 4
               THEN
                  l_dob := l_token;
               WHEN 5
               THEN
                  l_gender := l_token;
            END CASE;
         END IF;

         l_columnno := l_columnno + 1;
         l_token := NULL;
         l_enclosed := FALSE;
         l_new_token := TRUE;
         l_token_complete := FALSE;
      END IF;

      -- process end-of-line here
      IF l_line_complete
      THEN
         INSERT INTO app_debug
              VALUES (SYSTIMESTAMP, 'File Upload~' || l_lineno);

         DBMS_OUTPUT.put_line ('-----');

         IF l_lineno > 1
         THEN
            SELECT COUNT (*)
              INTO l_count
              FROM student_details
             WHERE id = l_id;

            IF l_count > 0
            THEN
               i_flag := 'U';

               UPDATE student_details
                  SET name = l_name,
                      address = l_address,
                      dob = l_dob,
                      gender = l_gender
                WHERE id = l_id;
            ELSE
               i_flag := 'I';

               INSERT INTO student_details (id,
                                            name,
                                            address,
                                            dob,
                                            gender)
                    VALUES (l_id,
                            l_name,
                            l_address,
                            l_dob,
                            l_gender);
            END IF;



            IF i_flag = 'I'
            THEN
               IF SQL%ROWCOUNT = 0
               THEN
                  NULL;
               -- not inserted
               ELSE
                  NULL;
               -- inserted
               END IF;
            END IF;

            IF i_flag = 'U'
            THEN
               IF SQL%ROWCOUNT = 0
               THEN
                  NULL;
               -- not updated
               ELSE
                  NULL;
               -- updated
               END IF;
            END IF;

            i_flag := NULL;
         END IF;


         l_lineno := l_lineno + 1;
         l_columnno := 1;
         l_line_complete := FALSE;
      END IF;
   END LOOP;

   UPDATE STUDENT_FILES
      SET IS_PROCESSED = 'Y'
    WHERE FILE_ID = p_id;
EXCEPTION
   WHEN OTHERS
   THEN
      UPDATE STUDENT_FILES
         SET IS_PROCESSED = 'E'
       WHERE FILE_ID = p_id;

      v_error :=
            'File Upload ~ Error at line no='
         || DBMS_UTILITY.format_error_backtrace
         || '-->'
         || SQLERRM;

      INSERT INTO app_debug
           VALUES (SYSTIMESTAMP, v_error);

      DBMS_OUTPUT.put_line (v_error);
END;


Friday, July 31, 2020

Redirect to another page using a button in Interactive Grid

function( options )
{
   var $ = apex.jQuery,
       toolbarData = $.apex.interactiveGrid.copyDefaultToolbar(), // Make a copy of the default toolbar
       actionsMenuGroup = toolbarData.toolbarFind( "actions1" );  // Locate the actions menu group

   // Array position denotes displayed position in the toolbar, so let's add the new download button directly
   // after the actions menu group in the array, such that it displays directly after the actions menu in the
   // toolbar.
   // Note: The toolbar is action-driven, so integrates easily with the Interactive Grid. To show the dialog, we
   // just define the appropriate action for showing the download dialog (show-download-dialog).
   actionsMenuGroup.controls.push( {
       type: "BUTTON",
       action: "show-download-dialog",
       iconBeforeLabel: true
   } );
   actionsMenuGroup.controls.push( {
       type: "BUTTON",
       action: "show-sort-dialog",
       iconBeforeLabel: true
   } );
 
 toolbarGroup = toolbarData[toolbarData.length - 1]; // this is the last group with reset button
   // add our own button
    toolbarGroup.controls.push( {
        type: "BUTTON",
        action: "my-action",
         hot:true 
    });
options.initActions = function( actions ) {
        // can modify state of existing actions or add your own
        // can also pass in an array of actions to add
        actions.add( {
            name: "my-action",
            label: "New",
            action: function(event, focusElement) {
         apex.navigation.redirect( "f?p=" + $v( "pFlowId" ) + ":6:" + $v( "pInstance" ) );

            }
        } );
    }
   // Assign new toolbar data back to toolbarData configuration property
   options.toolbarData = toolbarData;
 
   // Return the options
   return options;  
   
}



--------------------------

function(config) {  
    let $ = apex.jQuery,  
        toolbarData = $.apex.interactiveGrid.copyDefaultToolbar(), // copy the whole toolbar  
        toolbarGroup = toolbarData.toolbarFind("actions2"); // this is the group with the save button  
          
        ///  
       config.initActions = function( actions ) {  
        // Add new actions, either singularly passing in an actions object as shown here, or in  
        // multiple by passing an array of action objects  
        actions.add( {  
            name: "my-action",  
            action: function( event, focusElement ) {  
          //redirect to page in this application  set your URL accordingly  
            apex.navigation.redirect ( "f?p=&APP_ID.:1:&SESSION.::&DEBUG.:RP::" );  
                /***In case the Url above  is giving you some issues use this one***/  
//            apex.navigation.redirect( "f?p=" + $v( "pFlowId" ) + ":1:" + $v( "pInstance" ) );  
        } );  
    };     
    // add a new "redirect" button  
    toolbarGroup.controls.push({type: "BUTTON",  
                                iconBeforeLabel: true,  
                                hot: true,  
                                label: 'redirect',  
                                action: "my-action"  
                               });  
  
    //store the config  
    config.toolbarData = toolbarData;  
    return config;  
}  

How to split column data into rows in Oracle

SELECT REGEXP_SUBSTR (:P2_SELECTED_NODES,
                          '[^:]+',
                          1,
                          ROWNUM)
              ID
      FROM DUAL
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE (:P2_SELECTED_NODES, '[^:]+')) + 1;

Input: 1:2:3:4
Output: 
1
2
3
4

Thursday, July 30, 2020

Files Upload in Oracle APEX

Item -->  :P9_FILE_BROWSE  (File Browse)

-- Validation (V_FileFormat) --> Type: PL/SQL Function (returning error text)
DECLARE
   v_file   VARCHAR2 (1000);
BEGIN
   v_file := UPPER (TRIM ( :P9_FILE_BROWSE));

   IF LOWER (SUBSTR (v_file, INSTR (v_file, '.', -4) + 1)) IN ('jpeg',
                                                               'jpg',
                                                               'png',
                                                               'bmp',
                                                               'xls',
                                                               'xlsx',
                                                               'pdf')
   THEN
      NULL;
   ELSE
      RETURN 'Please upload jpeg/jpg/png/xls/xlsx/pdf format files only.';
   END IF;
END;

Buttons with icons in Oracle APEX

SAVE : <span aria-hidden="true" class="fa fa-save">&nbsp;Save</span>
CANCEL: <span aria-hidden="true" class="fa fa-times">&nbsp;Cancel</span>

Exclude columns while downloading the Interactive report data in Oracle APEX


SELECT T.CITYID,
         T.CITYID AS CITYID_DISPLAY,
         T.CITYNAME,
         COUNTRYID,
         (SELECT C.COUNTRYNAME
            FROM COUNTRY C
           WHERE C.COUNTRYID = T.COUNTRYID)
            AS COUNTRYNAME,
         'Delete' Del
    FROM CITIES T
ORDER BY UPPER (T.CITYNAME) ASC

To exclude CITYID while export/download from Interactive Report:

Select the column -->Server-Side Condition -->  Type (PL/SQL Expression) --> Paste below script

nvl(:request, 'EMPTY') not in ('CSV','XLS','PDF','RTF','HTMLD')
and nvl(wwv_flow.g_widget_action, 'EMPTY') <> 'SEND_EMAIL'

Monday, July 27, 2020

Client Side Error Messages in Oracle APEX

SAVE (button) --> Page Message (Dynamic Action) --> On Click (Event) --> TRUE event

/* General page error message */
apex.message.showErrors([
{
type: "error",
location: "page",
message: "Page error has occurred!",
unsafe: false
}
]);

/* Item error message */
apex.message.showErrors([
{
type: "error",
location: [ "page", "inline" ],
pageItem: "P7_CITYNAME",
message: "Value is required!",
unsafe: false
}
]);

/* Multi Item error message */
apex.message.clearErrors();
var chkErr = 0;
var arr = [
   'P7_CITYNAME',
   'P7_COUNTRYNAME'
];

for (var i in arr) {
  if ($v(arr[i]).length == 0) {
    apex.message.showErrors([
      {
        type: apex.message.TYPE.ERROR,
        location: ["inline"],
        pageItem: arr[i],
        message: "Value is required!",
        unsafe: false
      }
    ]);
    chkErr = 1;
  }
}

if ( chkErr == 0 ) {
  /* Custom dynamic action call when no error occurred */
  apex.event.trigger(document, 'customDA', [{customAttribute:'1'}]);
}

Saturday, July 25, 2020

Display Validations using Dynamic Actions in Oracle APEX

Button --> Dynamic Actions --> Event: Click --> True --> Execute Javascript Code

NOT NULL Check
*****************************************

if ($v('P7_CITYNAME')=== undefined || $v('P7_CITYNAME')== null || $v('P7_CITYNAME').length <= 0)
 {
    apex.message.alert('Please Enter City Name.');
}
if ($v('P7_COUNTRYNAME')=== undefined || $v('P7_COUNTRYNAME')== null || $v('P7_COUNTRYNAME').length <= 0)
 {
    apex.message.alert('Please Enter Country Name.');
}

or


if ($v('P7_CITYNAME') == "")
{
alert("Please Enter City Name.");
}
if ($v('P7_COUNTRYNAME') == "")
{
alert("Please Enter Country Name.");
}

Duplicate check
*************************************************
Execute PL/SQL Code

DECLARE
   v_dup   NUMBER (1) := 0;
BEGIN
   SELECT COUNT (*)
     INTO v_dup
     FROM CITIES
    WHERE CITYNAME = :P7_CITYNAME;

   IF v_dup > 0
   THEN
      :P7_CITYDUP := 'Y';
   ELSE
      :P7_CITYDUP := 'N';
   END IF;
END;


Items to Submit: P7_CITYNAME
Items to Return: P7_CITYNAME

Execute Javascript Code

var nameExists = $v('P7_CITYDUP') === 'Y';
var cityNull = $v('P7_CITYNAME') === '';

if (nameExists) {
  if (!cityNull) {
  alert('This City Name already exists. Please enter a different City Name');
}
}

Custom CSV Download button for Interactive Report


 While creating a button, 
 specify the option "Page in this application". 
 The page number should be same as the one where the Interactive report is created.
 In the Request text field, mention the "CSV" option. 
 
 That is all you need.

Delete Row Button for Interactive Report in Oracle Apex


1. Add One More Dummy Column to Interactive Report (City Details)

SELECT T.CITYID,
       T.CITYID AS CITYID_DISPLAY,
       T.CITYNAME,
       (SELECT C.COUNTRYNAME
          FROM COUNTRY C
         WHERE C.COUNTRYID = T.COUNTRYID)
          AS COUNTRYID,
       'Delete' Del
  FROM CITIES T
 
2. Set the Following Properties for the DEL Column

Type: Link
Heading: Delete
Target > Type: URL
URL: javascript:void(null);
Link Text: <span class="t-Icon fa fa-trash delete-irrow" aria-hidden="true"></span>
Link Attributes: data-id=#CITYID#

3. Create a Page Item to Hold the Primary Key Column Value

Now create a hidden page item to hold the primary key column P2_CITYID_H value. Do the right-click on the interactive report region and select Create Page Item option and set the following properties:

Name: P2_CITYID_H (set the name according to your page)
Type: Hidden
Value Protected: No

4. Create a Dynamic Action for the Interactive Report’s Delete Row Button

In Oracle Apex page designer, click on the Dynamic Actions Tab and do the right-click on the Click node and select Create Dynamic Action option and set the following properties:

Name: DA_DELETEROW
Event: Click
Selection Type: jQuery Selector
jQuery Selector: .delete-irrow
Event Scope: Dynamic

5. Create 4 True Actions for the Above Dynamic Action DA_DELETEROW

1st True action Confirm.
---------------------------------------
Do the right-click on the Dynamic Action DA_DELETEROW and select Create True Action option and set the following properties:
Action: Confirm
Text: Are you sure to delete this customer?

2nd True Action Set Value.
---------------------------------------
Create another True action Set Value below the Confirm action and set the following properties:
Action: Set Value
Set Type: JavaScript Expression
JavaScript Expression: $(this.triggeringElement).parent().data('id')
Selection Type: Item(s)
Item(s): P2_CITYID_H

3rd True Action Execute PL/SQL Code.
---------------------------------------
Create another True action Execute PL/SQL Code below the Set Value action and set the following properties:
Action: Execute PL/SQL Code
PL/SQL Code: Delete from CITIES where CITYID = :P2_CITYID_H;
Items to Submit: P2_CITYID_H

4th True Action Refresh.
--------------------------------
Create the last True action Refresh below the Execute PL/SQL Code action and set the following properties:
Action: Refresh
Selection Type: Region
Region: City Details (this is the interactive report region on my page)


The task is complete now, you have created the delete row button for the interactive report. Save the changes and run the page to test.


How to set the column width of Interactive reports in Oracle Apex


Region(Type Interactive Report) --> Report Attributes --> Column --> Static ID (Ex:scityid_display)


Page Inline:

th#scityid_display,
td[headers="scityid_display"]
{
   width: 150px;
}

th#scityname,
td[headers="scityname"]
{
   width: 150px;
}

th#scityid,
td[headers="scityid"]
{
   width: 150px;
}

th#scountryid,
td[headers="scountryid"]
{
   width: 150px;
}

Friday, July 24, 2020

Configuring Oracle Application Express to Send Email

Manage Instance --> Instance Settings --> Email

Application Express Instance URL : https://apex.oracle.com/pls/apex/
Application Express Images URL: https://apex.oracle.com/i/
SMTP Host Address :localhost
SMTP Host Port : 25
SMTP Authentication Username : ADMIN
SMTP Authentication Password : abcdefghijk
Use SSL/TLS : No
Default Email From Address :
Maximum Emails per Workspace : 1000

Customizing Interactive Grid Action Menu



add below script in  js path: Interactive Grid (Region Type) --> Attributes --> JavaScript Initialization Code

function(config)
{
    config.initActions = function( actions )
{
actions.remove("show-columns-dialog"); // Hides Columns
        actions.remove("show-filter-dialog"); // Hides Filter


//actions.hide("show-sort-dialog"); // Hides Sort inside "Data"
actions.hide("show-aggregate-dialog"); // Hides Aggregate inside "Data"
actions.hide("refresh"); // Hides Refresh inside "Data"

actions.hide("chart-view"); // Hides Chart.

actions.hide("show-save-report-as-dialog"); // Hides save as inside "Report"
actions.hide("show-edit-report-dialog"); // Hides edit inside "Report"

actions.remove("show-help-dialog"); // Hides Help
    }

config.features.flashback = false; // Hides Refresh inside "Flashback"

   var $ = apex.jQuery;
   var toolbarData = $.apex.interactiveGrid.copyDefaultToolbar();
   config.toolbarData = toolbarData;
   toolbarData[3].controls[0].menu.items[4]['hide'] = true; // Hides Format
   toolbarData[3].controls[0].menu.items[5]['hide'] = true; // Hides Selection
   toolbarData[3].controls[0].menu.items[8]['hide'] = true; // Hides Report

   return config;
}



--- to move options (Download and Sort) to right side of title bar
Region --> Attributes --> JavaScript Initialization Code

function( options )
{
   var $ = apex.jQuery,
       toolbarData = $.apex.interactiveGrid.copyDefaultToolbar(), // Make a copy of the default toolbar
       actionsMenuGroup = toolbarData.toolbarFind( "actions1" );  // Locate the actions menu group

   // Array position denotes displayed position in the toolbar, so let's add the new download button directly
   // after the actions menu group in the array, such that it displays directly after the actions menu in the
   // toolbar.
   // Note: The toolbar is action-driven, so integrates easily with the Interactive Grid. To show the dialog, we
   // just define the appropriate action for showing the download dialog (show-download-dialog).
   actionsMenuGroup.controls.push( {
       type: "BUTTON",
       action: "show-download-dialog",
       iconBeforeLabel: true
   } );
   actionsMenuGroup.controls.push( {
       type: "BUTTON",
       action: "show-sort-dialog",
       iconBeforeLabel: true
   } );
 
   // Assign new toolbar data back to toolbarData configuration property
   options.toolbarData = toolbarData;
 
   // Return the options
   return options;
}


-- adding hello button to beside Reset button

function(config) {
    var $ = apex.jQuery,
        toolbarData = $.apex.interactiveGrid.copyDefaultToolbar(),
        toolbarGroup = toolbarData[toolbarData.length - 1]; // this is the last group with reset button

    // add our own button
    toolbarGroup.controls.push( {
        type: "BUTTON",
        action: "my-action"
    });
    config.toolbarData = toolbarData;

    config.initActions = function( actions ) {
        // can modify state of existing actions or add your own
        // can also pass in an array of actions to add
        actions.add( {
            name: "my-action",
            label: "Hello",
            action: function(event, focusElement) {
                alert("Hello World!");
            }
        } );
    }
    return config;
}

-- combining action menu and tool bar

function( options )
{
   var $ = apex.jQuery,
       toolbarData = $.apex.interactiveGrid.copyDefaultToolbar(), // Make a copy of the default toolbar
       actionsMenuGroup = toolbarData.toolbarFind( "actions1" );  // Locate the actions menu group

   // Array position denotes displayed position in the toolbar, so let's add the new download button directly
   // after the actions menu group in the array, such that it displays directly after the actions menu in the
   // toolbar.
   // Note: The toolbar is action-driven, so integrates easily with the Interactive Grid. To show the dialog, we
   // just define the appropriate action for showing the download dialog (show-download-dialog).
   actionsMenuGroup.controls.push( {
       type: "BUTTON",
       action: "show-download-dialog",
       iconBeforeLabel: true
   } );
   actionsMenuGroup.controls.push( {
       type: "BUTTON",
       action: "show-sort-dialog",
       iconBeforeLabel: true
   } );
 
 toolbarGroup = toolbarData[toolbarData.length - 1]; // this is the last group with reset button
   // add our own button
    toolbarGroup.controls.push( {
        type: "BUTTON",
        action: "my-action"
    });
options.initActions = function( actions ) {
        // can modify state of existing actions or add your own
        // can also pass in an array of actions to add
        actions.add( {
            name: "my-action",
            label: "Hello",
            action: function(event, focusElement) {
                alert("Hello World!");
            }
        } );
    }
   // Assign new toolbar data back to toolbarData configuration property
   options.toolbarData = toolbarData;
 
   // Return the options
   return options;  
   
}

Tuesday, June 9, 2020

Read data from Nested Table in Oracle

SQL> CREATE OR REPLACE TYPE t_emp_no_name_obj AS OBJECT
  2  (
  3     NO NUMBER,
  4     NAME VARCHAR2 (100)
  5  );
  6  /

Type created.

SQL>
SQL> CREATE OR REPLACE TYPE t_emp_no_name_list IS TABLE OF t_emp_no_name_obj;
  2  /

Type created.

SQL>
SQL> SET SERVEROUTPUT ON;
SQL>
SQL> CREATE OR REPLACE FUNCTION f_emp_names
  2     RETURN t_emp_no_name_list
  3  AS
  4     v_emp_no_name_list   t_emp_no_name_list := t_emp_no_name_list ();
  5  BEGIN
  6     v_emp_no_name_list.DELETE ();
  7
  8     SELECT CAST (
  9               MULTISET (SELECT empno, ename FROM emp) AS t_emp_no_name_list)
 10       INTO v_emp_no_name_list
 11       FROM DUAL;
 12
 13     RETURN v_emp_no_name_list;
 14  EXCEPTION
 15     WHEN OTHERS
 16     THEN
 17        RETURN NULL;
 18        DBMS_OUTPUT.put_line ('Oracle Error Code=' || SQLCODE);
 19        DBMS_OUTPUT.put_line ('Oracle Error Message=' || SQLERRM);
 20  END f_emp_names;
 21  /

Function created.

SQL>
SQL> SELECT f_emp_names FROM DUAL;

F_EMP_NAMES(NO, NAME)
------------------------------------------------------------------------------------------------------------------------------------------------------
T_EMP_NO_NAME_LIST(T_EMP_NO_NAME_OBJ(7369, 'RAJ'), T_EMP_NO_NAME_OBJ(7499, 'ALLEN'), T_EMP_NO_NAME_OBJ(7521, 'WARD'), T_EMP_NO_NAME_OBJ(7566, 'JONES')
, T_EMP_NO_NAME_OBJ(7654, 'MARTIN'), T_EMP_NO_NAME_OBJ(7698, 'BLAKE'), T_EMP_NO_NAME_OBJ(7782, 'CLARK'), T_EMP_NO_NAME_OBJ(7788, 'SCOTT'), T_EMP_NO_NA
ME_OBJ(7839, 'KING'), T_EMP_NO_NAME_OBJ(7844, 'TURNER'), T_EMP_NO_NAME_OBJ(7876, 'ADAMS'), T_EMP_NO_NAME_OBJ(7900, 'JAMES'), T_EMP_NO_NAME_OBJ(7902, '
FORD'), T_EMP_NO_NAME_OBJ(7934, 'MILLER'))


SQL>
SQL> SELECT * FROM TABLE (SELECT f_emp_names FROM DUAL);

        NO NAME
---------- ----------------------------------------------------------------------------------------------------
      7369 RAJ
      7499 ALLEN
      7521 WARD
      7566 JONES
      7654 MARTIN
      7698 BLAKE
      7782 CLARK
      7788 SCOTT
      7839 KING
      7844 TURNER
      7876 ADAMS

        NO NAME
---------- ----------------------------------------------------------------------------------------------------
      7900 JAMES
      7902 FORD
      7934 MILLER

14 rows selected.

SQL>






Monday, May 25, 2020

Locks in Oracle

SELECT c.owner,
       c.object_name,
       c.object_type,
       b.sid,
       b.serial#,
       b.status,
       b.osuser,
       b.machine
  FROM v$locked_object a, v$session b, dba_objects c
 WHERE     b.sid = a.session_id
       AND a.object_id = c.object_id
       AND b.sid IN (SELECT l.session_id
                       FROM dba_lock_internal l
                      WHERE UPPER (l.lock_id1) LIKE '%ILP_REPORTS_PKG%');

SELECT c.owner,
       c.object_name,
       c.object_type,
       b.sid,
       b.serial#,
       b.status,
       b.osuser,
       b.machine
  FROM v$locked_object a, v$session b, dba_objects c
 WHERE b.sid = a.session_id AND a.object_id = c.object_id;

ALTER SYSTEM KILL SESSION 'sid,serial#';

SELECT    'ALTER SYSTEM KILL SESSION '''
       || SID
       || ','
       || SERIAL#
       || ',@1'
       || ''';'
  FROM gv$session
 WHERE status = 'ACTIVE' AND username = 'APEX_PUBLIC_USER';


SELECT * FROM v$access WHERE object IN ('P_ILAPERF_INT_SPLIT','P_ILAPERF_EXT_SPLIT')

select sid, event from v$session_wait where sid in (98,100);

/* Formatted on 6/20/2017 12:01:04 PM (QP5 v5.256.13226.35510) */
SELECT s.sid,
       l.lock_type,
       l.mode_held,
       l.mode_requested,
       l.lock_id1,
          'alter system kill session '''
       || s.sid
       || ','
       || s.serial#
       || ''' immediate;'
          kill_sid
  FROM dba_lock_internal l, v$session s
 WHERE     s.sid = l.session_id
       AND UPPER (l.lock_id1) LIKE '%ILA_PERFORMANCE_PKG%' --   AND l.lock_type = 'Body Definition Lock'

Wednesday, May 20, 2020

Adding double quote delimiters into csv file


1. open cmd and execute powershell.exe
2. run below command
import-csv D:\Test.csv | export-csv D:\Test_new.csv -NoTypeInformation -Encoding UTF8

Example:

D:\Test.csv

id,name,location
1,raj,Anantapur
2,siva,Hyderabad
3,venki,Bangalore

D:\Test_new.csv

"id","name","location"
"1","raj","Anantapur"
"2","siva","Hyderabad"
"3","venki","Bangalore"

Wednesday, May 13, 2020

View details of .p12 certificate on windows machine

C:\Users\rajam>certutil -dump D:\Oracle_2019\Certview\Certificates\wsctt_042020\wsctt-wsvcoraclectt.p12

Enter PFX password:

================ Certificate 0 ================

================ Begin Nesting Level 1 ================

Element 0:

Serial Number: 123456789999999

Issuer: CN=Pearson VUE Root Certificate Authority

 NotBefore: 7/28/2012 2:29 AM

 NotAfter: 7/28/2032 2:29 AM

Subject: CN= abc Root Certificate Authority

CA Version: V0.0

Signature matches Public Key

Root Certificate: Subject matches Issuer

Cert Hash(sha1): 123456789999999

----------------  End Nesting Level 1  ----------------

No key provider information

Cannot find the certificate and private key for decryption.



================ Certificate 1 ================

================ Begin Nesting Level 1 ================

Element 1:

Serial Number: 123456789999999

Issuer: CN= abc Root Certificate Authority

 NotBefore: 8/30/2012 1:26 AM

 NotAfter: 8/30/2022 1:36 AM

Subject: CN= abc CTT Certificate Authority, DC=abc, DC=com

CA Version: V0.0

Certificate Template Name (Certificate Type): SubCA

Non-root Certificate

Template: SubCA

Cert Hash(sha1): 123456789999999

----------------  End Nesting Level 1  ----------------

No key provider information

Cannot find the certificate and private key for decryption.



================ Certificate 2 ================

================ Begin Nesting Level 1 ================

Element 2:

Serial Number: 123456789999999

Issuer: CN= abc CTT Certificate Authority, DC=abc, DC=com

 NotBefore: 4/25/2020 1:16 AM

 NotAfter: 4/25/2021 1:16 AM

Subject: E=pvats@.com, CN=wsctt-wsvcoraclectt, OU=abc, O=NCS , L=Bloomington, S=Minnesota, C=US

Non-root Certificate

Cert Hash(sha1): 123456789999999       

----------------  End Nesting Level 1  ----------------

  Provider = Microsoft Enhanced Cryptographic Provider v1.0

Encryption test passed

CertUtil: -dump command completed successfully.



   

Wednesday, March 11, 2020

External Tables in Oracle


1. Place the ALL_OBJECTS.csv file in D:\CDD
2.  GRANT CREATE ANY DIRECTORY TO SCOTT;
3. Create directory

CREATE OR REPLACE DIRECTORY EXT_TAB_DATA AS 'D:\CDD';
SELECT * FROM ALL_DIRECTORIES WHERE DIRECTORY_NAME='EXT_TAB_DATA';

DROP TABLE ALL_OBJECTS_DUMP;

CREATE TABLE ALL_OBJECTS_DUMP (
    owner         VARCHAR2(30),
    object_name   VARCHAR2(30),
    object_type   VARCHAR2(19),
    status        VARCHAR2(7),
    created       DATE
)
organization EXTERNAL ( TYPE oracle_loader
    DEFAULT DIRECTORY ext_tab_data
ACCESS PARAMETERS (
    RECORDS DELIMITED BY NEWLINE
    FIELDS TERMINATED BY ',' MISSING FIELD VALUES ARE NULL
(
   owner       CHAR(30),
    object_name   CHAR(30),
    object_type   CHAR(19),
    status        CHAR(7),
    created       CHAR(10)
    )
  ) location('ALL_OBJECTS.csv') )
    PARALLEL 5
REJECT LIMIT UNLIMITED;

SELECT * FROM ALL_OBJECTS_DUMP;

Tuesday, March 3, 2020

Download Files in Oracle APEX



CREATE TABLE ATTACHEMENTS
(
   ID             NUMBER,
   ILE_NAME       VARCHAR2 (400),
   FILE_TYPE      VARCHAR2 (400),
   FILE_SIZE      VARCHAR2 (400),
   FILE_CONTENT   BLOB
);

Create a Apex Page with Region - PL/SQL Dynamic Content 

DECLARE
   v_mime         VARCHAR2 (200) := NULL;
   v_lob_length   NUMBER := 0;
   v_file         VARCHAR2 (100) := NULL;
   v_blobref      BLOB;
BEGIN
   SELECT T.FILE_NAME FILE_NAME,
          T.FILE_TYPE FILE_TYPE,
          DBMS_LOB.GETLENGTH (T.FILE_CONTENT) AS FILE_LENGTH,
          T.FILE_CONTENT
     INTO v_file,
          v_mime,
          v_lob_length,
          v_blobref
     FROM  << ATTACHMENTS>> T
    WHERE FILE_ID = 123;

   sys.HTP.init;
   sys.OWA_UTIL.mime_header (NVL (v_mime, 'application/octet'),
                             FALSE,
                             'UTF-8');
   sys.HTP.p ('Content-length: ' || v_lob_length);
   sys.HTP.p (
      'Content-Disposition: attachement; filename="' || v_file || '"');
   sys.OWA_UTIL.http_header_close;
   sys.WPG_DOCLOAD.download_file (v_blobref);
   APEX_APPLICATION.stop_apex_engine;
EXCEPTION
   WHEN OTHERS
   THEN
      sys.HTP.prn ('error: ' || SQLERRM);
      APEX_APPLICATION.stop_apex_engine;
END;

Monday, March 2, 2020

Shared Interactive Report with filters in Oracle APEX

Create a Interactive Report with below query.

SELECT EMPNO,
       ENAME,
       JOB,
       MGR,
       HIREDATE,
       SAL,
       COMM,
       DEPTNO
  FROM EMP;

Modify alias name of Primary Report to PRIMARY.



1. Primary Report

https://apex.oracle.com/pls/apex/f?p=120487:2:16532414902526:IR_PRIMARY::::

2. Resets, and clears primary report settings : 

https://apex.oracle.com/pls/apex/f?p=120487:2:16532414902526:IR_PRIMARY::RIR,CIR::

3. Resets, and clears primary report settings. It additionally creates a ENAME = 'KING' filter on the primary report:

https://apex.oracle.com/pls/apex/f?p=120487:2:16532414902526:IR_PRIMARY::RIR,CIR:IR_EMPNO:7521
https://apex.oracle.com/pls/apex/f?p=120487:2:16532414902526:IR_PRIMARY::RIR,CIR:IR_ENAME:KING
https://apex.oracle.com/pls/apex/f?p=120487:2:16532414902526:IR_PRIMARY::RIR,CIR:IR_JOB:SALESMAN
https://apex.oracle.com/pls/apex/f?p=120487:2:16532414902526:IR_PRIMARY::RIR,CIR:IR_SAL:5000
https://apex.oracle.com/pls/apex/f?p=120487:2:16532414902526:IR_PRIMARY::RIR,CIR:IR_DEPTNO:30

Valid operators include:

C = Contains
EQ = Equals (this is the default)
GTE = Greater than or equal to
GT = Greater Than
LIKE = SQL Like operator
LT = Less than
LTE = Less than or equal to
N = Null
NC = Not Contains
NEQ = Not Equals
NLIKE = Not Like
NN = Not Null
NIN = Not In (escape the comma separated values with a leading and trailing backslash, \)
IN = In (escape the comma separated values with a leading and trailing backslash, \)
ROWFILTER = Row Text Contains (this searches all columns displayed in the report with type STRING or NUMBER)

https://apex.oracle.com/pls/apex/f?p=120487:2:104896389797835:::RIR,CIR:IRIN_ENAME:\SMITH,KING\


Wednesday, February 12, 2020

Parameter Values in Oracle

SQL> SELECT VALUE
  2    FROM V$NLS_PARAMETERS
  3   WHERE parameter = 'NLS_DATE_FORMAT';

VALUE
----------------------------------------------------------------
DD-MON-RR

SQL> set pages 100
SQL> set lines 150
SQL> SELECT * FROM V$NLS_PARAMETERS;

PARAMETER                     VALUE
----------------------------- ------------------------------------
NLS_LANGUAGE                              AMERICAN
NLS_TERRITORY                              AMERICA
NLS_CURRENCY                              $
NLS_ISO_CURRENCY                      AMERICA
NLS_NUMERIC_CHARACTERS    .,
NLS_CALENDAR                             GREGORIAN
NLS_DATE_FORMAT                      DD-MON-RR
NLS_DATE_LANGUAGE                AMERICAN
NLS_CHARACTERSET                   AL32UTF8
NLS_SORT                                        BINARY
NLS_TIME_FORMAT                      HH.MI.SSXFF AM
NLS_TIMESTAMP_FORMAT         DD-MON-RR HH.MI.SSXFF AM
NLS_TIME_TZ_FORMAT               HH.MI.SSXFF AM TZR
NLS_TIMESTAMP_TZ_FORMAT  DD-MON-RR HH.MI.SSXFF AM TZR
NLS_DUAL_CURRENCY               $
NLS_NCHAR_CHARACTERSET   AL16UTF16
NLS_COMP                                       BINARY
NLS_LENGTH_SEMANTICS          BYTE
NLS_NCHAR_CONV_EXCP           FALSE

19 rows selected.

SQL>

Delete Row Button to all records of Interactive Report in Oracle Apex

 1. add 'Delete' Del column to Report Query 2. Set the Following Properties for the DEL Column Type: Link Heading: Delete Targ...