Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 7129

Proc to send email notification on new entry

$
0
0

Hi,

I have a stored proc that I want to modify...

This existing sto proc was supposed to send an email whenever there is a new entry to a report...

There is also an audit table to keep track of sent emails.

As it stands the proc does not run if the audit table is empty...

I dont know what I am doing wrong, need help figuring this out... (I cannot use SSIS or SSRS email capabilities)

USE [IIT_PRACTICUM]
GO

--Object:  StoredProcedure [dbo].[USP_sendemail]
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--CREATE PROCEDURE [dbo].[USP_psychosis_sendemail] (@EmailUser VARCHAR(MAX))
--AS
  -- ==========================================================================
  -- Object  :  pull data from a sql view includes the cases to be reported  
  --			within 30 days of the case being registered, send preceding data to end users via
  --			email notification on an hourly basis
  -- -------------------------------------------------------------------------

  BEGIN TRY;
      -- prevent SQL Server from sending row counts to the client
      -- ensure any user-defined transaction is rolled back if the client
      -- cancels the batch like query time-out
      SET NOCOUNT ON;
      SET XACT_ABORT ON;

      -- -------------------------------------------------------------------------- 
      -- get a list of emails that need to be sent and store in a temp table
      -- --------------------------------------------------------------------------
      --------------------------------------------------------------------------

    BEGIN TRAN
          DECLARE @RptLink AS TABLE
        (
           id         INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
           reportlink VARCHAR(max)
        ) ;
              DECLARE @EmailContent VARCHAR(max) ;
      DECLARE @LastSent DATETIME, @now DATETIME;
	  SET @now = GETDATE()

	  -- get the time when the job sent email last time
	  -- if there is no row in audit table, default the value to previous hour

      SET @LastSent = CASE WHEN (SELECT Max(run_time) FROM  dbo.[fep_pkg_audit]) IS NOT NULL
	                  THEN (SELECT Max(run_time) FROM dbo.[fep_pkg_audit])
					  ELSE Dateadd(hour, -1, @now)
					  END;
	 -- store the records with hyperlink format that need to be emailed to users into a temp table
      INSERT INTO @RptLink
      SELECT 'http://diitssrs01/ReportServer/Pages/ReportViewer.aspx?%2fIIT%2fInformatics_FirstEpisodePsychosis%2fDetailsRep&DoccID='+ CONVERT(VARCHAR(100), clinical_document_id) LinkTest
	  FROM   dbo.v_first_episode_psychosis
	  WHERE  submit_date BETWEEN @LastSent AND @now;

    -- --------------------------------------------------------------------------
    -- send emails when there are any records
    -- --------------------------------------------------------------------------
    -----------------------------------------------------------------------------
    IF (SELECT Count(*) FROM @RptLink) > 0
      BEGIN

--- store a list rows into a HTML table -------------------------------------

          SET @EmailContent = N'<table border="1">'+ N'<tr><th>ID</th><th>ReportLink</th></tr>'+ Cast (( SELECT td = id, '', td = reportlink, ''
								FROM
                              @RptLink FOR xml path('tr'), type ) AS NVARCHAR(
                              max) )+ N'</table>';
      END
      ELSE
      BEGIN
          SET @EmailContent = N'<table border="1">'+ N'<tr><th>ID</th><th>ReportLink</th></tr>'+ N'<tr><th>ID</th><th>No Content Found</th></tr>'+ N'</table>';
      END

	--- send email---------------------------------------------------------------

          EXEC msdb.dbo.Sp_send_dbmail
            @recipients = 'drele@health.com',
            @subject = 'Email Notification' ,
            @body = @EmailContent,
            @body_format = 'HTML' ;
            
          INSERT INTO [dbo].[fep_pkg_audit]
          SELECT 'IIT_EHR_REPORTINGSYSTEM_dataextract' AS pkg_name,
                 @now                                  AS run_time,
                 1                                     AS email_sent,
                 reportlink
          FROM   @RptLink ;
      
  COMMIT TRAN
END try
-- -------------------------------------------------------------------------- 
  BEGIN catch
      IF @@trancount > 0
        ROLLBACK TRANSACTION

      DECLARE @errmsg   NVARCHAR(2048),
              @severity TINYINT,
              @state    TINYINT,
              @errno    INT,
              @proc     SYSNAME,
              @lineno   INT;

      SELECT @errmsg = Error_message(),
             @severity = Error_severity(),
             @state = Error_state(),
             @errno = Error_number(),
             @proc = Error_procedure(),
             @lineno = Error_line();

      DECLARE @raisemsg VARCHAR(8000);

      SET @raisemsg = 'Error ' + @errmsg + ', Error Number '+ CONVERT(VARCHAR(5), @errno) + ', Severity '+ CONVERT(VARCHAR(5), @severity) + ', State '+ CONVERT(VARCHAR(5), @state) + ', Procedure '+ Isnull(@proc, '<dynamic SQL>') + ', Line '+ CONVERT(VARCHAR(5), @lineno);
      SET @raisemsg = @raisemsg + ':  ' + @errmsg;

      RAISERROR(@raisemsg,@severity,@state)
  END catch
-- --------------------------------------------------------------------------

GO
Thanks in advance for your help...


Dhananjay Rele


Viewing all articles
Browse latest Browse all 7129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>