SQL Server Agent - Unique ID for Each Job Execution - sql

I have this query that provides a lot of useful info for my scheduled jobs but there is one thing I am still missing. I am trying to locate a unique ID for every job execution, not the instance or schedule ID. Does this exist, and of so how would I join it to the current tables I'm using? Any assistance is appreciated.
Thanks!
Edit: I know I can create a unique ID for jobs that run once per day but most of the jobs run multiple time per day. Some run every 2 minutes.
SELECT h.instance_id
, j.job_id
,j.name AS JobName
,CASE
WHEN h.step_name = '(Job outcome)'
THEN 'Job Run Time'
ELSE h.step_name
END AS StepName
,h.step_id
,CAST(STR(h.run_date, 8, 0) AS DATETIME) + CAST(STUFF(STUFF(RIGHT('000000' + CAST(h.run_time AS VARCHAR(6)), 6), 5, 0, ':'), 3, 0, ':') AS DATETIME) AS StartDatetime
,DATEADD(SECOND, ((h.run_duration / 1000000 * 86400 + (h.run_duration - h.run_duration / 1000000 * 1000000) / 10000 * 3600) + (h.run_duration - h.run_duration / 10000 * 10000) / 100 * 60) + (h.run_duration - h.run_duration / 100 * 100), CAST(STR(h.run_date, 8, 0) AS DATETIME) + CAST(STUFF(STUFF(RIGHT('000000' + CAST(h.run_time AS VARCHAR(6)), 6), 5, 0, ':'), 3, 0, ':') AS DATETIME)) AS EndDatetime
,CASE
WHEN STUFF(STUFF(REPLACE(STR(h.run_duration, 6, 0), ' ', '0'), 3, 0, ':'), 6, 0, ':') > '23:59:00'
THEN '23:59:00'
ELSE STUFF(STUFF(REPLACE(STR(h.run_duration, 6, 0), ' ', '0'), 3, 0, ':'), 6, 0, ':')
END AS run_duration_formatted
,((h.run_duration / 1000000 * 86400 + (h.run_duration - h.run_duration / 1000000 * 1000000) / 10000 * 3600) + (h.run_duration - h.run_duration / 10000 * 10000) / 100 * 60) + (h.run_duration - h.run_duration / 100 * 100) AS RunDurationInSeconds
,CASE h.run_status
WHEN 0
THEN 'Failed'
WHEN 1
THEN 'Succeded'
WHEN 2
THEN 'Retry'
WHEN 3
THEN 'Cancelled'
WHEN 4
THEN 'In Progress'
END AS ExecutionStatus
FROM msdb.dbo.sysjobhistory AS h
INNER JOIN msdb.dbo.sysjobs AS j ON j.job_id = h.job_id
LEFT JOIN [msdb].[dbo].[sysjobactivity] A ON A.job_id = h.job_id
WHERE (j.enabled = 1)
AND A.session_id = 1053
AND (CAST(STR(h.run_date, 8, 0) AS DATETIME) + CAST(STUFF(STUFF(RIGHT('000000' + CAST(h.run_time AS VARCHAR(6)), 6), 5, 0, ':'), 3, 0, ':') AS DATETIME) >= DATEADD(dd, - 1, CAST(GETDATE() AS DATE)))
Order by instance_id

Maybe use with dense_rank() and using distinct?
SELECT distinct h.instance_id
, dense_rank() over (order by j.job_id, h.run_date, h.run_time)
, j.job_id
,j.name AS JobName
,CASE
WHEN h.step_name = '(Job outcome)'
THEN 'Job Run Time'
ELSE h.step_name
END AS StepName
,h.step_id
,CAST(STR(h.run_date, 8, 0) AS DATETIME) + CAST(STUFF(STUFF(RIGHT('000000' + CAST(h.run_time AS VARCHAR(6)), 6), 5, 0, ':'), 3, 0, ':') AS DATETIME) AS StartDatetime
,DATEADD(SECOND, ((h.run_duration / 1000000 * 86400 + (h.run_duration - h.run_duration / 1000000 * 1000000) / 10000 * 3600) + (h.run_duration - h.run_duration / 10000 * 10000) / 100 * 60) + (h.run_duration - h.run_duration / 100 * 100), CAST(STR(h.run_date, 8, 0) AS DATETIME) + CAST(STUFF(STUFF(RIGHT('000000' + CAST(h.run_time AS VARCHAR(6)), 6), 5, 0, ':'), 3, 0, ':') AS DATETIME)) AS EndDatetime
,CASE
WHEN STUFF(STUFF(REPLACE(STR(h.run_duration, 6, 0), ' ', '0'), 3, 0, ':'), 6, 0, ':') > '23:59:00'
THEN '23:59:00'
ELSE STUFF(STUFF(REPLACE(STR(h.run_duration, 6, 0), ' ', '0'), 3, 0, ':'), 6, 0, ':')
END AS run_duration_formatted
,((h.run_duration / 1000000 * 86400 + (h.run_duration - h.run_duration / 1000000 * 1000000) / 10000 * 3600) + (h.run_duration - h.run_duration / 10000 * 10000) / 100 * 60) + (h.run_duration - h.run_duration / 100 * 100) AS RunDurationInSeconds
,CASE h.run_status
WHEN 0
THEN 'Failed'
WHEN 1
THEN 'Succeded'
WHEN 2
THEN 'Retry'
WHEN 3
THEN 'Cancelled'
WHEN 4
THEN 'In Progress'
END AS ExecutionStatus
FROM msdb.dbo.sysjobhistory AS h
INNER JOIN msdb.dbo.sysjobs AS j ON j.job_id = h.job_id
LEFT JOIN [msdb].[dbo].[sysjobactivity] A ON A.job_id = h.job_id
WHERE (j.enabled = 1)
--AND A.session_id = 1053
AND (CAST(STR(h.run_date, 8, 0) AS DATETIME) + CAST(STUFF(STUFF(RIGHT('000000' + CAST(h.run_time AS VARCHAR(6)), 6), 5, 0, ':'), 3, 0, ':') AS DATETIME) >= DATEADD(dd, - 1, CAST(GETDATE() AS DATE)))
Order by j.job_id, instance_id

Edit: The table I used in this query is populated every 5 minutes with the data from the first query I posted.
OK, I couldn't find a unique ID for each schedule execution so I had to rethink what I could do. The query is below.
This solved my problem. I have a Google chart embedded in SharePoint that lists the jobs and the run times. Each bar represents how long the job took to run. Prior to this solution the chart only showed a failed status if the last step failed. Now with this incorporated I can see if any step failed withing each job execution. This is fantastic! In the image below you can see the red executions had a step failure within the job.
SELECT D.[instance_id]
,[JobName]
,[StepName]
,[step_id]
,[Run_Date]
,[StartDatetime]
,[StartTime]
,[EndDatetime]
,[End_Time]
,[Run_Duration_Formatted]
,[RunDurationInSeconds]
,MAX(CASE WHEN C.ExecutionStatus IS NULL THEN D.[ExecutionStatus] ELSE C.ExecutionStatus END) AS ExecutionStatus
FROM [STG_EDW].[dbo].[Job_Runs_FINAL] AS D
LEFT JOIN
(
SELECT Step0.Instance_ID
,'Failed' AS ExecutionStatus
FROM(
SELECT [instance_id]
,[JobName]
,[StartDatetime]
,[EndDatetime]
FROM [My Table]
WHERE step_id = 0) AS Step0
INNER JOIN(
SELECT Instance_ID, JobName, [StartDatetime], [EndDatetime]
FROM [My Table]
WHERE ExecutionStatus = 'Failed') AS B ON Step0.JobName = B.JobName AND B.StartDatetime >= Step0.StartDatetime AND B.EndDatetime <= Step0.EndDatetime
) AS C ON D.instance_id = C.instance_id
Group By D.[instance_id]
,[JobName]
,[StepName]
,[step_id]
,[Run_Date]
,[StartDatetime]
,[StartTime]
,[EndDatetime]
,[End_Time]
,[Run_Duration_Formatted]
,[RunDurationInSeconds]

Related

How do you do a where clause with a select statement as a value

I'm trying to get the total amount from the next month's record.
SELECT TOP (1000)
[DEMAND_POINT_ID],
[DPM_XREF_ID],
[UTIL_TYPE],
[ACCOUNT_ID],
[REV_YR_MNTH],
[TOTAL_AMOUNT],
(SELECT CAST(LEFT((SELECT CONVERT(varchar, DATEADD(month, 1, LEFT(REV_YR_MNTH, 4) + '-' + RIGHT(REV_YR_MNTH, 2) + '-' + '01'), 112)), 6) AS int)) AS nextmonth,
(SELECT de2.[TOTAL_AMOUNT]
FROM [DEQEnergyUsage].[dbo].[DST_ENERGY_USAGE_AGGR] de2
WHERE de2.ACCOUNT_ID = de.ACCOUNT_ID
AND de2.REV_YR_MNTH = (SELECT CAST(LEFT((SELECT CONVERT(varchar, DATEADD(month, 1, LEFT(REV_YR_MNTH, 4) + '-' + RIGHT(REV_YR_MNTH, 2) + '-' + '01'), 112)), 6) AS int))) AS nextamount
FROM
[DEQEnergyUsage].[dbo].[DST_ENERGY_USAGE_AGGR] de
WHERE
ACCOUNT_ID =1
ORDER BY
ACCOUNT_ID, de.REV_YR_MNTH
The value nextmonth creates the next month's rev_yr_mnth correctly however when I try to use this created value in the where clause it brings back nothing in the nextamount field.
It's like it does not recognize the created value as a true value. What do I need to do to have the where clause recognize the value?
Using CTE you can add condition on nextmonth.
With CTE As (
SELECT TOP (1000)
[DEMAND_POINT_ID],
[DPM_XREF_ID],
[UTIL_TYPE],
[ACCOUNT_ID],
[REV_YR_MNTH],
[TOTAL_AMOUNT],
(SELECT CAST(LEFT((SELECT CONVERT(varchar, DATEADD(month, 1, LEFT(REV_YR_MNTH, 4) + '-' + RIGHT(REV_YR_MNTH, 2) + '-' + '01'), 112)), 6) AS int)) AS nextmonth,
(SELECT de2.[TOTAL_AMOUNT]
FROM [DEQEnergyUsage].[dbo].[DST_ENERGY_USAGE_AGGR] de2
WHERE de2.ACCOUNT_ID = de.ACCOUNT_ID
AND de2.REV_YR_MNTH = (SELECT CAST(LEFT((SELECT CONVERT(varchar, DATEADD(month, 1, LEFT(REV_YR_MNTH, 4) + '-' + RIGHT(REV_YR_MNTH, 2) + '-' + '01'), 112)), 6) AS int))) AS nextamount
FROM
[DEQEnergyUsage].[dbo].[DST_ENERGY_USAGE_AGGR] de
WHERE
ACCOUNT_ID =1
ORDER BY
ACCOUNT_ID, de.REV_YR_MNTH
)
select * from CTE
-- Where nextmonth condition

SQL Query to get all clients birthdays for this month

I'm trying to create a query that will display all clients born this month, but I'm getting:
Conversion failed when converting date and/or time from character string."
Here is my code.
SELECT
t.Client_id, t.Name
FROM
(SELECT
Client_id,
C_name + ' ' + C_surname AS Name,
CONVERT(INT, SUBSTRING(Client_id, 3, 2)) AS M,
CONVERT(INT, SUBSTRING(Client_id, 5, 2)) AS D,
CONVERT(DATE, CONVERT(VARCHAR, CONVERT(CHAR(4), DATEPART(YEAR, GETDATE())) + '-' + SUBSTRING(Client_id, 3, 2) + '-' + SUBSTRING(Client_id, 5, 2))) AS DateOfBirth
FROM
tblClientInfo) T
WHERE
T.M <= 12
AND T.DateOfBirth = CONVERT(DATE, GETDATE());
I tried to put CONVERT(varchar, getdate()) but still getting error
This one works well for extracting birthdays for today only:
SELECT
t.Client_id, t.Name
FROM
(SELECT
Client_id,
C_name + ' ' + C_surname AS Name,
CONVERT(INT, SUBSTRING(Client_id, 3, 2)) AS M,
CONVERT(INT, SUBSTRING(Client_id, 5, 2)) AS D,
CONVERT(DATE, CONVERT(VARCHAR, CONVERT(CHAR(4), DATEPART(YEAR, GETDATE())) + '-' + SUBSTRING(Client_id, 3, 2) + '-' + SUBSTRING(Client_id, 5, 2))) AS DateOfBirth
FROM
tblClientInfo) T
WHERE
T.D <= 31
AND T.M <= 12
AND T.DateOfBirth = CONVERT(DATE, GETDATE());
Try this:
select *
from tblClientInfo
where CAST(SUBSTRING(Client_id, 3, 2) AS TINYINT) = month(getdate());
Hmmm . . . I'm thinking:
select c.*
from tblClientInfo c
where month(dateofbirth) = month(getdate());

Sql agent job last run status

I have N jobs with M steps in each, that could change any time(Add/delete some steps). Jobs have different schedule to run. I want a query to get last run status, job id, job name of each job. Is it right way to do this scenario by (Job outcome) ?
This is the query I use (a little tuned) to check job status. This variation will select the last job outcome for each job.
SELECT
JobName = J.name,
H.*
FROM
msdb.dbo.sysjobs AS J
CROSS APPLY (
SELECT TOP 1
JobName = J.name,
StepNumber = T.step_id,
StepName = T.step_name,
StepStatus = CASE T.run_status
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled'
ELSE 'Running' END,
ExecutedAt = msdb.dbo.agent_datetime(T.run_date, T.run_time),
ExecutingHours = ((T.run_duration/10000 * 3600 + (T.run_duration/100) % 100 * 60 + T.run_duration % 100 + 31 ) / 60) / 60,
ExecutingMinutes = ((T.run_duration/10000 * 3600 + (T.run_duration/100) % 100 * 60 + T.run_duration % 100 + 31 ) / 60) % 60,
Message = T.message
FROM
msdb.dbo.sysjobhistory AS T
WHERE
T.job_id = J.job_id
ORDER BY
T.instance_id DESC) AS H
ORDER BY
J.name
If you change the TOP 1 for TOP 2, then you will also see the last step executed, aside from the job outcome.
You can not get everything in a single query and need more research. For e.g., to know Job execution information you can try the following query.
SELECT
[sJOB].[job_id] AS [JobID]
, [sJOB].[name] AS [JobName]
, CASE
WHEN [sJOBH].[run_date] IS NULL OR [sJOBH].[run_time] IS NULL THEN NULL
ELSE CAST(
CAST([sJOBH].[run_date] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJOBH].[run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END AS [LastRunDateTime]
, CASE [sJOBH].[run_status]
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled'
WHEN 4 THEN 'Running' -- In Progress
END AS [LastRunStatus]
, STUFF(
STUFF(RIGHT('000000' + CAST([sJOBH].[run_duration] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS [LastRunDuration (HH:MM:SS)]
, [sJOBH].[message] AS [LastRunStatusMessage]
, CASE [sJOBSCH].[NextRunDate]
WHEN 0 THEN NULL
ELSE CAST(
CAST([sJOBSCH].[NextRunDate] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJOBSCH].[NextRunTime] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END AS [NextRunDateTime]
FROM
[msdb].[dbo].[sysjobs] AS [sJOB]
LEFT JOIN (
SELECT
[job_id]
, MIN([next_run_date]) AS [NextRunDate]
, MIN([next_run_time]) AS [NextRunTime]
FROM [msdb].[dbo].[sysjobschedules]
GROUP BY [job_id]
) AS [sJOBSCH]
ON [sJOB].[job_id] = [sJOBSCH].[job_id]
LEFT JOIN (
SELECT
[job_id]
, [run_date]
, [run_time]
, [run_status]
, [run_duration]
, [message]
, ROW_NUMBER() OVER (
PARTITION BY [job_id]
ORDER BY [run_date] DESC, [run_time] DESC
) AS RowNumber
FROM [msdb].[dbo].[sysjobhistory]
WHERE [step_id] = 0
) AS [sJOBH]
ON [sJOB].[job_id] = [sJOBH].[job_id]
AND [sJOBH].[RowNumber] = 1
ORDER BY [JobName]
You can get and learn in details - Here and Here

SQL Server : conversion failed when converting date and/or time from character with string past 12pm

For the past few days my code has worked, but today it has the following error:
Conversion failed when converting date and/or time from character string
Here is my code:
DECLARE #run_time INT
DECLARE #run_duration INT
SET #run_time = '120609'
SET #run_duration = '2600'
SELECT
h.step_id,
CAST(j.[name] AS VARCHAR) as JobName,
h.step_name,
CAST(REPLACE(LEFT(CAST(case
when len(#run_time) = 1 then '00:00:0' + cast(#run_time as varchar)
when len(#run_time) = 2 then '00:00:' + cast(#run_time as varchar)
when len(#run_time) = 3 then '00:0' + cast(left(#run_time,1) as varchar) + ':' + cast(right(#run_time,2) as varchar)
when len(#run_time) = 4 then '00:' + cast(left(#run_time,2) as varchar) + ':' + cast(right(#run_time,2) as varchar)
when len(#run_time) = 5 then '0' + cast(left(#run_time,1) as varchar) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 2, 2) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 4,2)
when len(#run_time) = 6 then cast(left(#run_time,2) as varchar) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 2,2) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 4,2)
END AS TIME), 8), ':', '') AS INT) StartTime
I discovered the only time the error appears is when the run_time goes past 120000 (12pm), hence why I've never noticed it before because the agent jobs have ran at 3am. It shouldn't be an issue in the future, but just in case it is I would like a fix for this. I can't find an example anywhere that's similar to my code. Unfortunately casting the results like this is the only way I can get a graph in SSRS to work. (INT > VARCHAR > TIME > INT).
edit - here is a better example of my code using one of the proposed answers:
SELECT
h.step_id,
CAST(j.[name] AS VARCHAR) as JobName,
h.step_name,
CAST(stuff(stuff(right('0000000' + h.run_time, 6), 5, 0, ':'), 3, 0, ':') as time)
FROM
msdb.dbo.sysjobs j
INNER JOIN msdb.dbo.sysjobhistory h ON j.job_id = h.job_id
Thanks,
If you are trying to calculate the start time from a string in HHMMSS format, then this method seems much simpler to me:
select cast(stuff(stuff(right('0000000' + str, 6), 5, 0, ':'), 3, 0, ':') as time)
from (values ('120609'), ('0'), ('1001')) v(str)
In your case the problem is the string which you are trying to convert: "12:20:60"
The converstion to TIME type fails.
DECLARE #run_time INT
DECLARE #run_duration INT
SET #run_time = '120609'
SET #run_duration = '2600'
SELECT
-- h.step_id,
--CAST(j.[name] AS VARCHAR) as JobName,
-- h.step_name,
--CAST(REPLACE(LEFT(CAST(
case
when len(#run_time) = 1 then '00:00:0' + cast(#run_time as varchar)
when len(#run_time) = 2 then '00:00:' + cast(#run_time as varchar)
when len(#run_time) = 3 then '00:0' + cast(left(#run_time,1) as varchar) + ':' + cast(right(#run_time,2) as varchar)
when len(#run_time) = 4 then '00:' + cast(left(#run_time,2) as varchar) + ':' + cast(right(#run_time,2) as varchar)
when len(#run_time) = 5 then '0' + cast(left(#run_time,1) as varchar) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 2,2) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 4,2)
when len(#run_time) = 6 then cast(left(#run_time,2) as varchar) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 2,2) + ':' + SUBSTRING(CAST(#run_time AS VARCHAR), 4,2)
END ,
SUBSTRING(CAST(#run_time AS VARCHAR), 4,2)
--AS TIME)
--,8), ':', '') AS INT) StartTime
Did you check this out?
How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?
The best solution should be the one proposed by Gordon
This works for me:
SELECT
h.step_id,
CAST(j.[name] AS VARCHAR) as JobName,
h.step_name,
-- CAST(stuff(stuff(right('0000000' + h.run_time, 6), 5, 0, ':'), 3, 0, ':') as time)
(h.run_time / 1000000) % 100 as hour,
(h.run_time / 10000) % 100 as minute,
(h.run_time / 100) % 100 as second,
(h.run_time % 100) * 10 as millisecond,
dateadd(hour, (h.run_time / 1000000) % 100, dateadd(minute, (h.run_time / 10000) % 100, dateadd(second, (h.run_time / 100) % 100, dateadd(millisecond, (h.run_time % 100) * 10, cast('00:00:00' as time(2))))))
FROM
msdb.dbo.sysjobs j
INNER JOIN msdb.dbo.sysjobhistory h ON j.job_id = h.job_id
Btw, the CAST drives to error for me, as well
In case you don't want to use the select statement:
DECLARE #run_time INT
DECLARE #time_result TIME
SET #run_time = '120609'
SET #time_result = dateadd(hour, (#run_time / 1000000) % 100, dateadd(minute, (#run_time / 10000) % 100, dateadd(second, (#run_time / 100) % 100, dateadd(millisecond, (#run_time % 100) * 10, cast('00:00:00' as time(2))))))
select #time_result

How to get 30 days from now from SQL table

I am doing my project in MVC4 using c# and sql.. I have a table MemberDetails which contain table
CREATE TABLE [dbo].[MemberDetails] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Mem_FirstNA] VARCHAR (100) NOT NULL,
[Mem_LastNA] VARCHAR (100) NOT NULL,
[Mem_Occ] VARCHAR (100) NOT NULL,
[Mem_DOB] DATETIME NOT NULL,
[Mem_Email] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
I just want to select the names and date of birth where whose birthday in next 30 days and I use the following query
SELECT
Mem_FirstNA, Mem_LastNA, Mem_DOB
FROM
MemberDetails
WHERE
Mem_DOB >= getdate() - 1 AND Mem_DOB <= getdate() + 30
Is that correct, I got 0 item selected , I use the following table.
1 Pal Software 08-03-1987 AM 12:00:00
3 mn Par Bussiness 19-10-1967 AM 12:00:00
4 man George Business 13-11-1956 AM 12:00:00
5 Smi Kan Housewife 22-10-1980 AM 12:00:00
try this
SELECT
Mem_FirstNA, Mem_LastNA, Mem_DOB
FROM
MemberDetails
WHERE DAYOFYEAR(Mem_DOB)-DAYOFYEAR(getdate())<=30
Updated
SELECT
Mem_FirstNA, Mem_LastNA, Mem_DOB
FROM
MemberDetails
WHERE
DATEDIFF(DAY, GETDATE(), DATEADD(YEAR, DATEDIFF(YEAR, Mem_DOB, GETDATE()), Mem_DOB)) BETWEEN 0 AND 30
SELECT
Mem_FirstNA, Mem_LastNA, Mem_DOB
FROM
MemberDetails
WHERE
Mem_DOB >= Cast(current_timestamp As Date) AND Mem_DOB < DATEADD(d, 30, Cast(current_timestamp As Date));
Should work. Between usage was removed based on comments.
Will work for January birth dates as well
DECLARE #now DATETIME
SET #now = GETDATE()
SELECT Mem_FirstNA, Mem_LastNA, Mem_DOB
FROM MemberDetails
WHERE
CASE WHEN month(Mem_DOB) = 1
THEN DATEADD(YY, YEAR(DATEADD(DAY, 30, DATEADD(m, month(#now) - 1, DAY(#now) - 1))) - 1900, DATEADD(m, month(Mem_DOB) - 1, DAY(Mem_DOB) - 1))
ELSE DATEADD(m, month(Mem_DOB) - 1, DAY(Mem_DOB) - 1)
END
> DATEADD(m, month(#now) - 1, DAY(#now) - 1)
AND
CASE WHEN month(Mem_DOB) = 1
THEN DATEADD(YY, YEAR(DATEADD(DAY, 30, DATEADD(m, month(#now) - 1, DAY(#now) - 1))) - 1900, DATEADD(m, month(Mem_DOB) - 1, DAY(Mem_DOB) - 1))
ELSE DATEADD(m, month(Mem_DOB) - 1, DAY(Mem_DOB) - 1)
END
< DATEADD(DAY, 30, DATEADD(m, month(#now) - 1, DAY(#now) - 1))
Hope it helps
Try this
SELECT
Mem_FirstNA, Mem_LastNA, Mem_DOB
FROM
MemberDetails
WHERE
WHERE DATEPART(mm,Mem_DOB) BETWEEN DATEPART(mm,getDate()) AND DATEPART(mm,getDate())+1;
why not use this where clause:
WHERE MEM_DOB BETWEEN GETDATE()-1 AND GETDATE()+30
Try this...
SELECT
Mem_FirstNA, Mem_LastNA, Mem_DOB
FROM
MemberDetails
WHERE
ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' + ltrim(str(day(Mem_DOB))) >= getdate() - 1 AND ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' + ltrim(str(day(Mem_DOB))) <= getdate() + 30
EDIT: The comments for this answer have rightly pointed out that it will not work if the current year is a leap year. So this update. The list of dates can be more efficiently generated by using Get a list of dates between two dates using a function
Select Mem_FirstNA, Mem_LastNA, Mem_DOB from MemberDetails m, (
Select datepart(dd,getdate()) as d, datepart(mm,getdate()) as m
union
Select datepart(dd,getdate() + 1) as d, datepart(mm,getdate() + 1) as m
union
Select datepart(dd,getdate() + 2) as d, datepart(mm,getdate() + 2) as m
union
Select datepart(dd,getdate() + 3) as d, datepart(mm,getdate() + 3) as m
union
Select datepart(dd,getdate() + 4) as d, datepart(mm,getdate() + 4) as m
union
Select datepart(dd,getdate() + 5) as d, datepart(mm,getdate() + 5) as m
union
Select datepart(dd,getdate() + 6) as d, datepart(mm,getdate() + 6) as m
union
Select datepart(dd,getdate() + 7) as d, datepart(mm,getdate() + 7) as m
union
Select datepart(dd,getdate() + 8) as d, datepart(mm,getdate() + 8) as m
union
Select datepart(dd,getdate() + 9) as d, datepart(mm,getdate() + 9) as m
union
Select datepart(dd,getdate() + 10) as d, datepart(mm,getdate() + 10) as m
union
Select datepart(dd,getdate() + 11) as d, datepart(mm,getdate() + 11) as m
union
Select datepart(dd,getdate() + 12) as d, datepart(mm,getdate() + 12) as m
union
Select datepart(dd,getdate() + 13) as d, datepart(mm,getdate() + 13) as m
union
Select datepart(dd,getdate() + 14) as d, datepart(mm,getdate() + 14) as m
union
Select datepart(dd,getdate() + 15) as d, datepart(mm,getdate() + 15) as m
)X
where
datepart(dd, m.Mem_DOB) = x.d and datepart(mm, m.Mem_DOB) = x.m
If you are downvoting, please comment why.