SQL - Run second Query if count result = 0 - sql

Both my SELECT queries work below and return values with as two separate results. What I would like to do is if the first SELECT statement returns a 0 and it will sometimes due to the nature of our work, I would like the second to run ignoring the first one that returns zero if possible. IF the first one returns a result greater than zero then I do not want the second to run.
I have been all over looking and tried different IF ELSE and such but because of the specific date/time formulas used I am thinking it may not be possible or I this may have to be re-written altogether. There is a purpose for this but I will not bore you. Thanks in advance!
Declare #StartDate as DateTime
Declare #EndDate as DateTime
Declare #TodaysDate as DateTime
Declare #Previous as DateTime
Declare #Previous2 as DateTime
set #TodaysDate = GETDATE()
set #Previous = DATEADD(day,-1,#TodaysDate)
set #Previous2 = DATEADD(day,-2,#TodaysDate)
-- SELECT Statetment one starts here
set #StartDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous)) + '-' +
convert(varchar(2), datepart(dd, #Previous)) + ' ' +
'05:00' as datetime)
set #EndDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous)) + '-' +
convert(varchar(2), datepart(dd, #Previous)) + ' ' +
'16:59' as datetime)
SELECT Count(*) as FirstShfitPrevious
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
-- Query 2 Starts, Declarations already made at beginning
set #StartDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous2)) + '-' +
convert(varchar(2), datepart(dd, #Previous2)) + ' ' +
'05:00' as datetime)
set #EndDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous2)) + '-' +
convert(varchar(2), datepart(dd, #Previous2)) + ' ' +
'16:59' as datetime)
SELECT Count(*) as FirstShfitPrevious2
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate

You can try to store the value of your first query result in a variable and then then check the value like
declare #myVar int
SELECT #myVar = Count(*) as FirstShfitPrevious
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate)
if(#myVar = 0)
//Here your second query logic
begin
set #StartDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous2)) + '-' +
convert(varchar(2), datepart(dd, #Previous2)) + ' ' +
'05:00' as datetime)
set #EndDate = cast(convert(varchar(4), datepart(yyyy, getdate())) + '-' +
convert(varchar(2), datepart(mm, #Previous2)) + '-' +
convert(varchar(2), datepart(dd, #Previous2)) + ' ' +
'16:59' as datetime)
SELECT Count(*) as FirstShfitPrevious2
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
end

use NOT Exists..
if NOT Exists
(Select 1 as FirstShfitPrevious--first query
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
)
Begin
SELECT Count(*) as FirstShfitPrevious2--second query
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
END
Else
Begin
--First query
End

or even that way:
SELECT TOP 1 Count(*) as FirstShfitPrevious2
FROM [TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component]
WHERE Close_Time_Stamp between #StartDate and #EndDate
GROUP BY CAST(Close_Time_Stamp AS DATE)
ORDER BY CAST(Close_Time_Stamp AS DATE) DESC
with period covering both date ranges.

Related

Get calendar week id in sql

i want to get current and current - 7 week id in sql server.
So far i can get that, but for week id under 10 is a problem for me.
DECLARE #CurrentWeek nvarchar(6),#CurrentWeek7 nvarchar(6)
SET #CurrentWeek = CAST(datepart(yy, GETDATE()) AS CHAR(4))+''+CAST(datepart(ww, GETDATE()) AS CHAR(2))
SET #CurrentWeek7 = CAST(datepart(yy, DATEADD(WEEK, -7, GETDATE())) AS CHAR(4)) +''+CAST(datepart(ww, DATEADD(WEEK, -7, GETDATE())) AS CHAR(2))
Problem is that i get for example calendar week id without 0 between year and week number for week number under 10.
20199 instead of 201909. I want this to work also for week number bigger than 10, for example 201911
You can use the RIGHT trick to force a left-sided 0 when the week day is 9 or less.
DECLARE
#CurrentWeek nvarchar(6),
#CurrentWeek7 nvarchar(6)
DECLARE #TodayLastWeek DATE = DATEADD(DAY, -7, GETDATE())
SET #CurrentWeek = CONVERT(VARCHAR(4), DATEPART(YEAR, GETDATE()))
+ RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(WEEK, GETDATE())), 2)
SET #CurrentWeek7 = CONVERT(VARCHAR(4), DATEPART(YEAR, #TodayLastWeek))
+ RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(WEEK, #TodayLastWeek)), 2)
SELECT
CurrentWeek = #CurrentWeek,
CurrentWeek7 = #CurrentWeek7
Result:
CurrentWeek CurrentWeek7
201909 201908
PD: Please check Panagiotis' comment, his solution is faster and simpler.
I am thinking of logic like this:
DECLARE #CurrentWeek nvarchar(6),
#CurrentWeek7 nvarchar(6);
SET #CurrentWeek = dateadd(day,
1 - datepart(weekday, getdate()),
convert(date, getdate())
);
SET #CurrentWeek7 = dateadd(week, -7, #CurrentWeek);
The key idea is that the historical week should be based on the definition of the current week.
DECLARE #CurrentWeek nvarchar(6),#CurrentWeek7 nvarchar(6)
SET #CurrentWeek = CAST(datepart(yy, GETDATE()) AS CHAR(4))* 100+''+CAST(datepart(ww, GETDATE()) AS CHAR(2))
SET #CurrentWeek7 = CAST(datepart(yy, DATEADD(WEEK, -7, GETDATE())) AS CHAR(4))* 100 +''+CAST(datepart(ww, DATEADD(WEEK, -7, GETDATE())) AS CHAR(2))

replace calendar dateto/from with year,month,day dropdown menus in ssrs

best way to do this would be to have parameters which link the day dropdown column to the month one so that there are correct days in every month?
You would also need to use your Year parameter for a leap day in February.
I would use a table of dates based on your other parameters:
DECLARE #YEAR AS INT = 2016 --FOR DEV/TESTING - REFERENCE PARAMETERS
DECLARE #MONTH AS INT = 2 --FOR DEV/TESTING
DECLARE #START_DATE DATE = CAST(#YEAR AS VARCHAR(4)) + '-' + RIGHT('0' + CAST(#MONTH AS VARCHAR(2)), 2) + '-' + '01'
DECLARE #END_DATE DATE = DATEADD(DAY, -1, DATEADD(MONTH, 1, #START_DATE))
;WITH GETDATES AS
(
SELECT #START_DATE AS THEDATE
UNION ALL
SELECT DATEADD(DAY,1, THEDATE) FROM GETDATES
WHERE THEDATE < #END_DATE
)
SELECT DAY(GETDATES.THEDATE) AS DAYS FROM GETDATES
OPTION (maxrecursion 0)

How to show PRINT results in EXCEL

A team member and I re-wrote a query we posted here due to issues; using various sources from provided answers from my previous question as well as checking other solutions and the query works now as intended. HOWEVER we need to embed this query and run in the background (we already have) into an EXCEL sheet but the issue is we need to somehow actually display the results in the cell. The PRINT function of the query actually pops up a window in EXCEL when we run (DUH, as intended) but what we would like to do is some how show the PRINTED results. Since the query is run automagically inside the spreadsheet the option to export from SSMS to a file then retrieve from there is not an option since OUR DBA is pretty funky on what we do with the DB we cannot run as a job..etc.... Any help again would be appreciated.
Declare #StartDate1 as DateTime
Declare #StartDate2 as DateTime
Declare #EndDate1 as DateTime
Declare #EndDate2 as DateTime
Declare #TodaysDate1 as DateTime
Declare #TodaysDate2 as DateTime
Declare #Yesterday as DateTime
Declare #TotalRecords1 int = 7
Declare #TotalRecords2 int = 7
set #TodaysDate1 = GETDATE()
set #TodaysDate2 = #TodaysDate1
set #Yesterday = DATEADD(day,-1,#TodaysDate1)
-------------------------------------------------------------------
-- For AM Shift Data Readings --
-------------------------------------------------------------------
set #StartDate1 = cast(convert(varchar(4), datepart(yyyy, #Yesterday)) + '-' +
convert(varchar(2), datepart(mm, #Yesterday)) + '-' +
convert(varchar(2), datepart(dd, #Yesterday)) + ' ' +
'17:00' as datetime)
set #EndDate1 = cast(convert(varchar(4), datepart(yyyy, #TodaysDate1)) + '-' +
convert(varchar(2), datepart(mm, getdate())) + '-' +
convert(varchar(2), datepart(dd, getdate())) + ' ' +
'04:59' as datetime)
-------------------------------------------------------------------
-- For PM Shift Data Readings --
-------------------------------------------------------------------
set #StartDate2 = cast(convert(varchar(4), datepart(yyyy, #Yesterday)) + '-' +
convert(varchar(2), datepart(mm, #Yesterday)) + '-' +
convert(varchar(2), datepart(dd, #Yesterday)) + ' ' +
'05:00' as datetime)
set #EndDate2 = cast(convert(varchar(4), datepart(yyyy, #Yesterday)) + '-' +
convert(varchar(2), datepart(mm, #Yesterday)) + '-' +
convert(varchar(2), datepart(dd, #Yesterday)) + ' ' +
'16:59' as datetime)
--------Material Scan Table--------
SELECT
#TotalRecords1=(SELECT Count(*) FROM [Piston_TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component] WHERE Close_Time_Stamp between #StartDate1 and #EndDate1),
#TotalRecords2=(SELECT Count(*) FROM [Piston_TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component] WHERE Close_Time_Stamp between #StartDate2 and #EndDate2)
WHILE #TotalRecords1 = 0 AND #TotalRecords2 = 0
BEGIN
set #TodaysDate1 = DATEADD(day,-1,#TodaysDate1)
set #TodaysDate2 = DATEADD(day,-1,#TodaysDate2)
set #Yesterday = DATEADD(day,-1,#TodaysDate1)
-------------------------------------------------------------------
-- For AM Shift Data Readings --
-------------------------------------------------------------------
set #StartDate1 = cast(convert(varchar(4), datepart(yyyy, #Yesterday)) + '-' +
convert(varchar(2), datepart(mm, #Yesterday)) + '-' +
convert(varchar(2), datepart(dd, #Yesterday)) + ' ' +
'17:00' as datetime)
set #EndDate1 = cast(convert(varchar(4), datepart(yyyy, #TodaysDate1)) + '-' +
convert(varchar(2), datepart(mm, getdate())) + '-' +
convert(varchar(2), datepart(dd, getdate())) + ' ' +
'04:59' as datetime)
-------------------------------------------------------------------
-- For PM Shift Data Readings --
-------------------------------------------------------------------
set #StartDate2 = cast(convert(varchar(4), datepart(yyyy, #TodaysDate2)) + '-' +
convert(varchar(2), datepart(mm, getdate())) + '-' +
convert(varchar(2), datepart(dd, getdate())) + ' ' +
'05:00' as datetime)
set #EndDate2 = cast(convert(varchar(4), datepart(yyyy, #TodaysDate2)) + '-' +
convert(varchar(2), datepart(mm, getdate())) + '-' +
convert(varchar(2), datepart(dd, getdate())) + ' ' +
'16:59' as datetime)
SELECT
#TotalRecords1=(SELECT Count(*) FROM [Piston_TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component] WHERE Close_Time_Stamp between #StartDate1 and #EndDate1),
#TotalRecords2=(SELECT Count(*) FROM [Piston_TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component] WHERE Close_Time_Stamp between #StartDate2 and #EndDate2)
IF (SELECT Count(*) FROM [Piston_TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component] WHERE Close_Time_Stamp between #StartDate1 and #EndDate1) > 0
BREAK
ELSE
IF (SELECT Count(*) FROM [Piston_TOL_PROD_DB].[dbo].[tblLOT_CTRL_Active_Component] WHERE Close_Time_Stamp between #StartDate2 and #EndDate2) > 0
BREAK
ELSE
CONTINUE
END
PRINT '1st Shift LOT Trace Scans ending'
PRINT #EndDate2
PRINT #TotalRecords2
PRINT ' '
PRINT '2nd Shift LOT Trace Scans ending'
PRINT #EndDate1
PRINT #TotalRecords1
THESE ARE THE ACTUAL RESULTS from run query in SSMS we would like to somehow get EXCEL to show:
1st Shift LOT Trace Scans ending
Jul 6 2016 4:59PM
64
2nd Shift LOT Trace Scans ending
Jul 7 2016 4:59AM
73
You could try saving these into a table variable instead of printing them as follows:
declare #msgTable table ( msg varchar(100));
insert into #msgTable values ('1st Shift LOT Trace Scans ending');
insert into #msgTable values (#EndDate2);
select * from #msgTable;
and then right clicking the results and clicking Save results as to a csv file or a tab delimited file both of which you can open in excel.
So after a long weekend and help from the team we were able to get the results in EXCEL we want and pretty simple really. All we needed to do instead of PRINT was use CONCAT. I thought since we did eventually arrive at a conclusion I would post here. Though the answer above is also a somewhat solution the one I am posting here works more to our liking to avoid have to export the data when we can import automatically via the query. Thanks to all who chimed in!See bellow:
SELECT CONCAT ( '1st Shift ', #StartDate1, ' Total Scans ', #TotalRecords1, ' and ' +
'2nd Shift ', #StartDate2, ' Total Scans ', #TotalRecords2 ) as LotTrace
And the result was:
LotTrace
1st Shift Jul 11 2016 5:00PM Total Scans 105 2nd Shift Jul 11 2016 5:00AM Total Scans 77

how can I convert a date var to a number is sql?

I have this statements
SELECT #startdate = DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -7) -- Monday of previous week
SELECT #enddate = DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -1) -- Sunday of previous week
and I want to convert #startdate and #enddate to numbers in the following format 'yyyymmdd'
SELECT CONVERT(nvarchar(8), #StartDate, 112)
Will convert 2014-03-31 to 20140331
The easiest way is to use year(), month(), and day():
select #startdate = year(getdate())*10000 + month(getdate()) * 100 + day(getdate())
Use CONVERT
declare #enddate smalldatetime
SELECT #enddate = DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -1)
select convert(varchar(30), #enddate, 112)
This will work for you:
SELECT CAST(DATEPART(yyyy,#startdate) AS VARCHAR(4)) +
RIGHT('0' + CAST(DATEPART(mm,#startdate) AS VARCHAR(2)),2) +
RIGHT('0' + CAST(DATEPART(dd,#startdate) AS VARCHAR(2)),2)
But this is better:
SELECT CONVERT(nvarchar(8), #StartDate, 112)

SQL Query - Have to determine if it is a specific day of the month (ex: 2 Tuesday of month)

I have an app that allows users schedule an action to occur in the future. For example, that can select a date and schedule it to run on that day every month (ex: the 15th of each month). However, I now need to allow them to select a week day and week of the month. For example, they need to run an action the first friday of the month. Therefore I am allowing the to select the weekday (monday, tuesday, wednesday....) and week of the month (1st, 2nd, 3rd, 4th or 5th).
Here is the query I currently use:
Declare #nowString varchar(19)
Declare #nowDateString varchar(19)
Declare #now datetime
Declare #lastMinute datetime
Declare #nowDate datetime
Set #nowString = '#currentDateTime#:00'
Set #nowDateString = LEFT(#nowString, 10)
set #now = #nowString
set #nowDate = DATEADD(dd, 0, DATEDIFF(dd, 0, #now))
set #lastMinute = DATEADD(mi, -1, #now)
select *
from message_prepared
where schedule = '1'
and active = '1'
and noaa = '0'
and (
(
schedule_type = 'recurring'
and startdate <= #nowDate
and isnull(enddate, DATEADD(yy, 1, #nowDate)) >= #nowDate
and (
#nowDateString + ' ' + isnull(recurring_start_time_hour, '00') + ':' + isnull(recurring_start_time_min, '00') + ':00' = #now
or #nowDateString + ' ' + isnull(recurring_start_time_hour, '00') + ':' + isnull(recurring_start_time_min, '00') + ':00' = #lastMinute
)
-- Test for different type of recurring
and (
( ltrim(rtrim(recurring)) = 'M' and DATEPART(dd, startdate) = DATEPART(dd, #now) )
or ( ltrim(rtrim(recurring)) = 'W' and DATEPART(dw, startdate) = DATEPART(dw, #now) )
or ltrim(rtrim(recurring)) = 'D'
)
)
or (
schedule_type = 'once'
and startdate = #nowDate
and (
#nowDateString + ' ' + onetime_start_time_hour + ':' + onetime_start_time_min + ':00' = #now
or #nowDateString + ' ' + onetime_start_time_hour + ':' + onetime_start_time_min + ':00' = #lastMinute
)
)
)
and repeat_multiple_times = 0
UNION ALL
SELECT *
FROM MESSAGE_PREPARED
WHERE schedule = '1'
AND active = 1
AND noaa = 0
AND recurring = 'D'
AND repeat_multiple_times = 1
AND startDate IS NOT NULL
AND recurring_start_time_hour IS NOT NULL
AND recurring_start_time_hour < 24
AND recurring_start_time_min IS NOT NULL
AND recurring_start_time_min < 60
AND startdate <= #nowDate
AND ISNULL(enddate, DATEADD(yy, 1, #nowDate)) >= #nowDate
AND
(
CASE WHEN repeat_unit = 'M'
THEN
DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) % repeat_interval
ELSE
DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) % (repeat_interval * 60)
END = 0
OR
CASE WHEN repeat_unit = 'M'
THEN
(DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) - 1) % repeat_interval
ELSE
(DATEDIFF(n,
CONVERT(DATETIME,
CAST(DATEPART(yyyy, startDate) AS VARCHAR(4)) + '-' +
CAST(DATEPART(mm, startDate) AS VARCHAR(2)) + '-' +
CAST(DATEPART(dd, startDate) AS VARCHAR(2)) + ' ' +
CAST(recurring_start_time_hour AS VARCHAR(2)) + ':' +
CAST(recurring_start_time_min AS VARCHAR(2)) + ':00', 20),
GETDATE()) - 1) % (repeat_interval * 60)
END = 0
)
This will only occur when reocurring is set to "M" and I would like to determine if today is the specific day of the week, week of the month and hour/min.
This is pretty simple logic. Today is the nth DOW of the month when the following is true:
Today is that day of the week
The day of the month is between 7*(n-1) + 1 and 7 * n
So, the first Monday of the month is always between the 1st and 7th, and so on. Here is an example case statement to test this:
declare #DayOfWeek varchar(255) = 'Thursday';
declare #Which int = 3;
select (case when datename(dw, Today) = #DayOfWeek and
(DAY(Today) - 1) / 7 = #Which - 1
then 1
else 0
end)
from (select CAST(getdate() as date) as Today) t
I've structured the query this way so you can test it with different values. Just replace the expression that defines Today, with something like getdate() - 3 or '2013-01-01'.