Thursday, May 17, 2018

fnRequireEmail: Check if email need to be sent

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnRequireEmail]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnRequireEmail]
GO

/*
Sunday=1, Monday=2, ....Saturday=6
*/
CREATE FUNCTION [dbo].[fnRequireEmail]
(
@Date Datetime,
  @EmailCode dbo.EmailCode
)
RETURNS bit
BEGIN
declare
@result bit = 0,
@IsActive bit,
@EmailFreqType dbo.EmailFreqType,
@EmailFreqInterval dbo.EmailFreqInterval

select
@IsActive = IsActive,
@EmailFreqType = EmailFreqType,
@EmailFreqInterval = EmailFreqInterval
from dbo.SettingEmail
where EmailCode = @EmailCode

if ISNULL(@IsActive, 0) = 0
begin
return @result
end

if ISNULL(@EmailFreqType, '') IN ('Daily', '')
begin
set @result = 1
end
else if @EmailFreqType = 'Weekly'
begin
declare @dayOfWeek int
set @dayOfWeek = (DATEPART(dw, @Date) + @@DATEFIRST) % 7

IF CHARINDEX(',' + CAST(@dayOfWeek AS VARCHAR) + ',', ',' + @EmailFreqInterval + ',') > 0
begin
set @result = 1
end
end
else if @EmailFreqType = 'Monthly'
begin
declare @dayOfMonth int
set @dayOfMonth = DAY(@Date)

IF CHARINDEX(',' + CAST(@dayOfMonth AS VARCHAR) + ',', ',' + @EmailFreqInterval + ',') > 0
begin
set @result = 1
end
end

  return @result
END
GO

--select dbo.fnRequireEmail('2018-02-06', 'Job_Report')

No comments: