Sending sql output to email body with conditional subject line


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Sending sql output to email body with conditional subject line
# 1  
Old 03-13-2017
Sending sql output to email body with conditional subject line

hi ,

i have written below piece of code to meet the requirement but i am stuck in the logic here.

the requirement are:
1) to send the sql out put to email body with proper formatting.
2) if count_matching = Yes then mail should triggered with the subject line as "load counts Match for 'yyyymmdd'
else
"warning : load_count mismatch for 'yyyymmdd'"

please provide any other alternate solution if any..

thanks in advance



=====================

Code:
#!/usr/bin/ksh

sqlplus -s abc/yaho12@xyz <<EOF
set feedback off trimspool on
set linesize 2000;
set newpage 0;
SET PAGESIZE 0;
set wrap on;
SET ECHO OFF;
SET HEADING OFF;
SET VERIFY OFF;
whenever sqlerror exit failure;
whenever oserror exit failure;
alter session enable parallel dml;
spool output.txt;
select 'load_DATE'  || '    ' ||
         'SOURCE_NAME'   || '    ' ||
         'COUNTS_MATCHING' 
from dual
union all
select load_DATE|| '               ' ||
       DL_SOURCE_NAME   || '            ' ||
       COUNTS_MATCHING 
from 
(SELECT        load_DATE,
                   SOURCE_NAME,
               CASE WHEN CNT1=CNT2 THEN 'Yes' ELSE 'No' END COUNTS_MATCHING
          FROM
         (
             select load_DATE,
                     SOURCE_NAME,
                   TABLE_ROW_COUNT AS CNT1,
                   INPUT_RECORD_CNT AS CNT2       
             from T1
             WHERE INSERT_DATE = TRUNC(SYSDATE)
         )
 );
spool off;
exit;
EOF


more output.txt | mail -s "load counts Match for $( date '+%d/%m/%Y' )" sk@xyz.com

=====================

Last edited by Corona688; 03-13-2017 at 03:44 PM..
# 2  
Old 03-13-2017
To keep the forums high quality for all users, please take the time to format your posts correctly.

First of all, use Code Tags when you post any code or data samples so others can easily read your code. You can easily do this by highlighting your code and then clicking on the # in the editing menu. (You can also type code tags [code] and [/code] by hand.)



Second, avoid adding color or different fonts and font size to your posts. Selective use of color to highlight a single word or phrase can be useful at times, but using color, in general, makes the forums harder to read, especially bright colors like red.

Third, be careful when you cut-and-paste, edit any odd characters and make sure all links are working property.

Thank You.

The UNIX and Linux Forums
# 3  
Old 03-13-2017
What do you mean by 'proper formatting'? What are you expecting and what do you get? To get strict formatting of text you may have to surround it with <pre>formatted text</pre> tags or send the email as an attachment.

The use of more especially may add newlines you didn't want. Just
Code:
<output.txt mail -s "load counts Match for $( date '+%d/%m/%Y' )"  sk@xyz.com

should be sufficient.

Or perhaps
Code:
( echo "<pre>" ; cat output.txt ; echo "</pre>" ) | mail -s "load counts Match for $( date '+%d/%m/%Y' )"  sk@xyz.com

(a rare useful use of cat on a single file).
# 4  
Old 03-13-2017
Quote:
Originally Posted by itzkashi
...
...
2) if count_matching = Yes then mail should triggered with the subject line as "load counts Match for 'yyyymmdd'
else
"warning : load_count mismatch for 'yyyymmdd'"
...
...
Code:
...
 ...
 select 'load_DATE'  || '    ' ||
         'SOURCE_NAME'   || '    ' ||
         'COUNTS_MATCHING' 
from dual
union all
select load_DATE|| '               ' ||
       DL_SOURCE_NAME   || '            ' ||
       COUNTS_MATCHING 
from 
(SELECT        load_DATE,
                   SOURCE_NAME,
               CASE WHEN CNT1=CNT2 THEN 'Yes' ELSE 'No' END COUNTS_MATCHING
          FROM
         (
            select load_DATE,
                     SOURCE_NAME,
                   TABLE_ROW_COUNT AS CNT1,
                   INPUT_RECORD_CNT AS CNT2       
             from T1
             WHERE INSERT_DATE = TRUNC(SYSDATE)
         )
 );
...
 ...

...
...
Few more questions:

1) About the part of your logic in blue, did you mean:
a) Send an email with subject line: "warning: load counts mismatch for yyyymmdd" and the report as the email body, or
b) Do not send an email and just print "warning: ..." to stdout?

2) Will the part of your query in red return only one record?
- If it returns 4 records and 2 of them have counts_matching = "Yes" and the other 2 have counts_matching = "No", then what should be the final value of counts_matching?
# 5  
Old 03-13-2017
hi ,

thanks for reply . please let me know if more info is required,

1) About the part of your logic in blue, did you mean:
a) Send an email with subject line: "warning: load counts mismatch for yyyymmdd" and the report as the email body, or
b) Do not send an email and just print "warning: ..." to stdout? --no

--> in either case we need to send the report as the email body with the subject based on the output.


2) Will the part of your query in red return only one record? -- no , more than one record is also possible.
- If it returns 4 records and 2 of them have counts_matching = "Yes" and the other 2 have counts_matching = "No", then what should be the final value of counts_matching?

--> in this case if all the counts_matching records = 'Yes' then subject line should be as "load counts Match for 'yyyymmdd' "
else if any of the counts_matching records = 'No' then subject line should be as ""warning : load_count mismatch for 'yyyymmdd'" but report should contain all the counts_matching records.
# 6  
Old 03-14-2017
Quote:
Originally Posted by itzkashi
...
...
2) Will the part of your query in red return only one record? -- no , more than one record is also possible.
- If it returns 4 records and 2 of them have counts_matching = "Yes" and the other 2 have counts_matching = "No", then what should be the final value of counts_matching?

--> in this case if all the counts_matching records = 'Yes' then subject line should be as "load counts Match for 'yyyymmdd' "
else if any of the counts_matching records = 'No' then subject line should be as ""warning : load_count mismatch for 'yyyymmdd'" but report should contain all the counts_matching records.
So, in order to determine the appropriate mail subject, you want to find out if all records had counts matching or not.

The following query returns 1 if all records inserted today in table t1 have identical values for table_row_count and input_record_cnt.
If at least one record has different values, then the query returns 0.

Code:
select case when sum(case when table_row_count = input_record_cnt then 1 else 0 end) = count(*)
            then 1 else 0
       end as x
  from t1
 where insert_date = trunc(sysdate);

Of course, I assume that all both these columns (table_row_count and input_record_cnt) have numeric datatype, integer values and are non-nullable.
If NULLs are involved, then things become complicated pretty quickly.
- If one value is NULL and the other is, say, 5 then is that a mismatch or do you want to exclude them from comparison altogether, since NULL means "absence of value"?
- If both values are NULLs then is that a match or a mismatch?
Oracle has a lot of quirks regarding NULLs and I've avoided them in my suggested query.

Once you have this query, you can spool its output to another file and then read the said file to determine your mail subject.

Here's the shell script.
Note that I am echoing the mail command instead of executing it since I cannot email from my system.

Code:
$ 
$ 
$ cat -n generate_report.sh
     1	#!/usr/bin/ksh
     2	
     3	sqlplus -s user/pswd@db <<EOF
     4	set feedback off trimspool on
     5	set linesize 2000
     6	set newpage 0
     7	set pagesize 0
     8	set wrap on
     9	set echo off
    10	set verify off
    11	set time off timing off
    12	whenever sqlerror exit failure
    13	whenever oserror exit failure
    14	alter session enable parallel dml;
    15	spool output.txt
    16	SELECT 'LOAD_DATE SOURCE_NAME COUNTS_MATCHING'
    17	  FROM dual
    18	UNION ALL
    19	SELECT load_date || ' ' || source_name || ' ' ||
    20	       CASE WHEN table_row_count = input_record_cnt THEN 'Yes' ELSE 'No' END
    21	  FROM t1
    22	 WHERE insert_date = TRUNC(SYSDATE);
    23	spool off
    24	spool all_counts_match.txt
    25	select case when sum(case when table_row_count = input_record_cnt then 1 else 0 end) = count(*)
    26	            then 1 else 0
    27	       end as x
    28	  from t1
    29	 where insert_date = trunc(sysdate);
    30	spool off
    31	exit
    32	EOF
    33	
    34	if [[ $(cat all_counts_match.txt) -eq 1 ]]; then
    35	    mail_subject="Load counts match for $(date '+%d/%m/%Y')"
    36	else
    37	    mail_subject="Warning: Load counts do not match for $(date '+%d/%m/%Y')"
    38	fi
    39	echo "mail -s \"$mail_subject\" sk@xyz.com < output.txt"
    40	
$ 
$ 
$ . generate_report.sh
LOAD_DATE SOURCE_NAME COUNTS_MATCHING
01-JAN-17 SRC_1 Yes
01-FEB-17 SRC_2 Yes
01-MAR-17 SRC_3 Yes
	 1
mail -s "Load counts match for 13/03/2017" sk@xyz.com < output.txt
$ 
$ 
$ # After making a change in the data of the Oracle table so that the counts do not match...
$ 
$ . generate_report.sh
LOAD_DATE SOURCE_NAME COUNTS_MATCHING
01-JAN-17 SRC_1 Yes
01-FEB-17 SRC_2 No
01-MAR-17 SRC_3 Yes
	 0
mail -s "Warning: Load counts do not match for 13/03/2017" sk@xyz.com < output.txt
$ 
$

# 7  
Old 03-14-2017
hi ,

thanks i am able to get the desired output but only issue is with the formatting below since the source_name length varies .


Code:
LOAD_DATE SOURCE_NAME COUNTS_MATCHING
01-JAN-17 SRC_14568        Yes
01-FEB-17 SRC_2322  Yes
01-MAR-17 SRC_334343443434 Yes

expected output
---------------------
Code:
LOAD_DATE SOURCE_NAME     COUNTS_MATCHING
01-JAN-17    SRC_14568                  Yes
01-FEB-17    SRC_2322                   Yes
01-MAR-17    SRC_334343443434           Yes


Moderator's Comments:
Mod Comment Please use CODE tags as required by forum rules!

Last edited by itzkashi; 03-14-2017 at 11:34 AM.. Reason: Added CODE tags.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Red Hat

Sending email with message body and attachment

Hello experts!! I am trying to send an email with message body and attachment.but i am getting any one like message body or attachment. I tried below command: (echo "subject:test";echo "MIME-Version: 1.0";echo "content-transfer-encoding:base 64";echo "content-type:txt;name=test.txt";cat... (2 Replies)
Discussion started by: Devipriya Ch
2 Replies

2. Shell Programming and Scripting

Message Body while sending an email

I am making use of the following code to display the results of my txt file in an email: mail -s 'Count Validation Test Comparison Results' Ronit@XYZ.com < Count_Validation_Results_`date +%m%d%Y`.txt Email Output: ----------Query 1 Count Validation Results-------- Source count is 4 Target... (7 Replies)
Discussion started by: ronitreddy
7 Replies

3. Shell Programming and Scripting

Body content is in random format while sending email from Linux to my outlook.

Hi I have a script running in lunix machine which emails log file content to my outlook. Here is the actual log file result: Image-1 In-Master:25028 ReplicaDn Consumer Supplier Delay dc=xxx,dc=com lmjker0110:12345 ... (4 Replies)
Discussion started by: buzzme
4 Replies

4. Shell Programming and Scripting

Shell scripting unable to send the sql query data in table in body of email

I have written a shell script that calls below sql file. It is not sending the query data in table in the body of email. spool table_update.html; SELECT * FROM PROCESS_LOG_STATS where process = 'ActivateSubscription'; spool off; exit; Please use code tags next time for your code and data.... (9 Replies)
Discussion started by: Sharanakumar
9 Replies

5. Shell Programming and Scripting

SQL query output convert to HTML & send as email body

Hi , I have a sql query in the unix script ,whose output is shown below.I want to convert this output to HTML table format & send email from unix with this table as email body. p_id src_system amount 1 A 100 2 B 200 3 C ... (3 Replies)
Discussion started by: jagadeeshn04
3 Replies

6. Shell Programming and Scripting

Sending an email with a body and attachments using uuencode

Hi, Im having a bit of an issue with using the uuencode command and sending out an email. My aim is to send an email out which has a body and also have attachments. Currently I can either get one or the other and not both on the same email. uuencode... (4 Replies)
Discussion started by: 02JayJay02
4 Replies

7. AIX

Sending script output as email

Hi i have a script which executes daily through cron. The output of the script is appended to a log file everyday It also emails me the output of the logfile as we have the mailx command in the script The below is my requirement : Normally When I get the email it sends the entire content... (3 Replies)
Discussion started by: newtoaixos
3 Replies

8. UNIX for Dummies Questions & Answers

Sending email with attachment and body

Hi I want to able to attach a file to a email and send it with a body the body of the email is within the "body" file, and the attachment in "atch" if i send like below it will send the email correctly /usr/sbin/sendmail me@you.com< body And when i send the attachment alone... (3 Replies)
Discussion started by: sridanu
3 Replies

9. Shell Programming and Scripting

Not able to attach text in body of email while sending mail with attachment

Hi, We have been trying to send mail with attachment and it is going fine, but when we try to attach a text to the body of the email, we find that the mail is going fine with the body text but the attachment is not going through. We are using ksh. The command that is successfull without the... (6 Replies)
Discussion started by: jmathew99
6 Replies

10. Shell Programming and Scripting

Sending one email for every row as per sql result

I want to send email for every row comes out of following SQL statement thank you for your help. *****SQL STATEMENT****** Select SCUSER AS "USER IDS" , SCEUSER AS "LOCKED OUT" FROM SYS.7333.F98OWSEC; *******OUPUT COMES LIKE THIS AND ONE EMAIL COMES AS PER SCRIPT BELOW****** ******BUT... (4 Replies)
Discussion started by: s1a2m3
4 Replies
Login or Register to Ask a Question