I am looking to create a TSQL Parameter for specific timeframes such as MorningTimeFrame will pull yesterday from 4PM until noon today and AfternoonTimeFrame to pull noon today until 4Pm Today. How would I set that up? I'm familiar with the Dateadd(day,datediff(day,1,GETDATE()),0) but not sure how I would set it to a specific time.
You can get these required timeframe values as per below query
Select Cast(Cast(CAST(dateadd(d,-1,getdate()) AS date) as varchar) + ' 16:00:00' as datetime)AS 'MorningStartTime', Cast(Cast(CAST(getdate() AS date) as varchar) + ' 12:00:00' as datetime)AS 'MorningEndAfterNoonStartTime', Cast(Cast(CAST(getdate() AS date) as varchar) + ' 16:00:00' as datetime)AS 'AfterNoonEndTime'
Use this as per convenience
Will something simple suffice?
declare #Start as DateTime, #End as DateTime;
declare #Timeframe as VarChar(32) = 'MorningTimeframe';
-- Start from midnight today.
declare #Today as DateTime = Cast( GetDate() as Date );
-- Calculate the timeframe.
if #Timeframe = 'MorningTimeframe'
begin -- Yesterday 4PM through noon today.
select #Start = DateAdd( hour, -8, #Today ),
#End = DateAdd( hour, 12, #Today );
end
else if #Timeframe = 'AfternoonTimeframe'
begin -- Noon today through 4PM.
select #Start = DateAdd( hour, 12, #Today ),
#End = DateAdd( hour, 16, #Today );
end
else
begin
RaIsError( 'Unexpected timeframe: ''%s''', 16, 42, #Timeframe );
end;
-- Display the results.
select #Today as [Today], #Timeframe as Timeframe, #Start as [Start], #End as [End];
Related
I am trying to generate a stock position report as at each month. within my query i have a date variable set at a specific month:
declare #date datetime = CONVERT(DATETIME, '2019-08-13 00:00:00', 121)
declare #lastmonth datetime = (select cast(dateadd(day, -day(getdate()), getdate()) as date))
declare #m int = 0
--**my aim is to ensure that #date = #lastmonth**
while #date<= #lastmonth
Begin
set #m = #m + 1
while #m < 12
Begin
set #date = (select dateadd(mm, #m, #date))
End
End
select
I have a problem about sql query. Now I have GETDATE() FOR example today is wednesday, I need to have date between tho monday nights. and GETDATE() will be in this two date
Example today is thursday 18.05.2017 I want date between 15.05.2017 and 22.05.2017
I couldn't find any solution. How can I write it in where statement in query.
SELECT * FROM MATCHES
WHERE ...
Thanks in advance
To receive first monday:
SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 0)
and second one:
SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()) + 1, 0)
http://joelabrahamsson.com/getting-the-first-day-in-a-week-with-t-sql/
also
Get first day of week in SQL Server
here is the solution
firstly create a calendar table then
declare #startDate datetime = dateadd(week, datediff(week, 0, getdate()), 0);
declare #endDate datetime = DATEADD(DAYS,7,#startDate)
SELECT Date
FROM dbo.Calendar
WHERE Date >= #startDate
AND Date < #endDate ;
Create a Calendar Table if not exists
IF EXISTS (SELECT * FROM information_schema.tables WHERE Table_Name =
'Calendar' AND Table_Type = 'BASE TABLE')
BEGIN
DROP TABLE [Calendar]
END
CREATE TABLE [Calendar]
(
[CalendarDate] DATETIME
)
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
SET #StartDate = GETDATE()
SET #EndDate = DATEADD(d, 365, #StartDate)
WHILE #StartDate <= #EndDate
BEGIN
INSERT INTO [Calendar]
(
CalendarDate
)
SELECT
#StartDate
SET #StartDate = DATEADD(dd, 1, #StartDate)
END
Then, Use below query to get the output
declare #start datetime = dateadd(week, datediff(week, 0, getdate()), 0);
declare #end datetime = DATEADD(DAY,8,#start)
SELECT [CalendarDate]
FROM Calendar
WHERE CalendarDate BETWEEN #start AND #end
I have used below code to convert a datetime to string,
DECLARE #StartDate datetime = '08/07/2015 12:10 AM'
set #StartDate = dateadd(hour,12, #StartDate);
select CONVERT(VARCHAR(10),#StartDate, 101) + RIGHT(STUFF(CONVERT(VARCHAR(32), #StartDate,100), 18, 0, ' '),8)
but I am getting output as "08/07/201512:10 PM" , there is no space between date and time, How can I correct this?
If i correctly understood your problem then there is small correction required in your code. I added +' '+ i.e. a blank space between your date convert and right stuff. Complete code is as given below.
DECLARE #StartDate DATETIME = '08/07/2015 12:10 AM'
SET #StartDate = DATEADD(HOUR,12, #StartDate);
SELECT CONVERT(VARCHAR(10),#StartDate, 101) +' '+
RIGHT(STUFF(CONVERT(VARCHAR(32),#StartDate,100), 18, 0, ' '),8)
Result
08/07/2015 12:10 PM
i.e. space between date and time also space between 12:10 and PM
To cover new case provided :
DECLARE #StartDate DATETIME = '08/07/2015 2:10 AM'
SET #StartDate = DATEADD(HOUR,12, #StartDate);
SELECT CONVERT(VARCHAR(10),#StartDate, 101) +' '+
LTRIM(RIGHT(STUFF(CONVERT(VARCHAR(32),#StartDate,100), 18, 0, ' '),8))
Result
08/07/2015 2:10 PM
i.e. no extra space when time is like 2:10 PM
Here is one way to do it:
DECLARE #StartDate datetime = '2015-08-07T00:10:00';
SET #StartDate = dateadd(hour,12, #StartDate);
SELECT #StartDate As StartDate,
CONVERT(CHAR(10), #StartDate, 101) + ' ' + -- DateString,
SUBSTRING(CONVERT(CHAR(19), #StartDate, 100), 13, 5) + ' ' + -- TimeString
RIGHT(CONVERT(CHAR(19), #StartDate, 100), 2) As DateString -- AM/PM
Result:
StartDate DateString
----------------------- -------------------
2015-08-07 12:10:00.000 08/07/2015 12:10 PM
The following snippet will produce the output you've indicated in the question.
SET DATEFORMAT MDY;
DECLARE #StartDate DATETIME = '08-07-2015 12:10 AM';
SET #StartDate = DATEADD(HOUR, 12, #StartDate);
SELECT CONVERT(VARCHAR, #StartDate, 103) + ' ' +
CONVERT(VARCHAR, CAST(#StartDate AS TIME), 108) +
CASE WHEN DATEPART(HOUR, #StartDate) < 12 THEN ' AM' ELSE ' PM' END;
N.B. As others have pointed out, you would be better off using ISO format for input dates.
Updated dateformat from DMY to MDY and explicitly adding AM/PM to the end.
I need to display dates of all Mondays in the given date range.
For example, if my start date is 01/05/2015 and end date is 31/05/2015, I need to show
04/05/2015
11/05/2015
18/05/2015
25/05/2015
How is it possible?
This procedure is independent from regions and languages.
Please note the first line with SET DATEFIRST 1.
SET DATEFIRST 1; -- First day of the week is set to monday
DECLARE #DateFrom DateTime ='20150601', #DateTo DateTime = '20150630' ;
WITH CTE(dt)
AS
(
SELECT #DateFrom
UNION ALL
SELECT DATEADD(d, 1, dt) FROM CTE
WHERE dt < #DateTo
)
SELECT dt FROM CTE where datepart ("dw", dt) = 1;
Using a CTE it is possible this way..
DECLARE #DateFrom DateTime ='2015-05-01',
#DateTo DateTime = '2015-05-31'
;WITH CTE(dt)
AS
(
SELECT #DateFrom
UNION ALL
SELECT DATEADD(d, 1, dt) FROM CTE
WHERE dt < #DateTo
)
SELECT 'Monday', dt FROM CTE
WHERE DATENAME(dw, dt) In ('Monday')
Refer: Select dates of a day between two dates.
SELECT [Day],[Dt] FROM dbo.fnGetDatesforAday('7/1/2008','8/31/2008','Sunday')
CREATE FUNCTION fnGetDatesforAday
(
-- Add the parameters for the function here
#DtFrom DATETIME,
#DtTo DATETIME,
#DayName VARCHAR(12)
)
RETURNS #DateList TABLE ([Day] varchar(20),Dt datetime)
AS
BEGIN
IF NOT (#DayName = 'Monday' OR #DayName = 'Sunday' OR #DayName = 'Tuesday' OR #DayName = 'Wednesday' OR #DayName = 'Thursday' OR #DayName = 'Friday' OR #DayName = 'Saturday')
BEGIN
--Error Insert the error message and return
INSERT INTO #DateList
SELECT 'Invalid Day',NULL AS DAT
RETURN
END
DECLARE #TotDays INT
DECLARE #CNT INT
SET #TotDays = DATEDIFF(DD,#DTFROM,#DTTO)-- [NO OF DAYS between two dates]
SET #CNT = 0
WHILE #TotDays >= #CNT -- repeat for all days
BEGIN
-- Pick each single day and check for the day needed
IF DATENAME(DW, (#DTTO - #CNT)) = #DAYNAME
BEGIN
INSERT INTO #DateList
SELECT #DAYNAME,(#DTTO - #CNT) AS DAT
END
SET #CNT = #CNT + 1
END
RETURN
END
SET DATEFIRST 7; -- Set's sunday as first day of week, won't work otherwise
DECLARE #StartDate DATE = '06/01/2015'
DECLARE #EndDate DATETIME = '06/30/2015'
DECLARE #TableOfDates TABLE(DateValue DATETIME)
DECLARE #CurrentDate DATETIME
SET #CurrentDate = #startDate
WHILE #CurrentDate <= #endDate
BEGIN
INSERT INTO #TableOfDates(DateValue) VALUES (#CurrentDate)
SET #CurrentDate = DATEADD(DAY, 1, #CurrentDate)
END
SELECT * FROM #TableOfDates WHERE DATEPART(weekday,Datevalue) = 2
I am trying to get the date difference in a given date excluding the week days.
Here is what I have:
SELECT DATEADD (w, -4, GETDATE())
This returns 2013-05-04 19:01:53.170, which means that it also counts weekends.
Same for
SELECT DATEADD (dw, -4, GETDATE())
Any help will be appreciated.
Thanks in advance.
I'm using these functions that return the non-weekend seconds between two dates:
CREATE FUNCTION [dbo].[DateDiff_NoWeekends](
#date1 DATETIME,
#date2 DATETIME
)
RETURNS INT AS BEGIN
DECLARE #retValue INT
SET #date1 = dbo.__CorrectDate(#date1, 1)
SET #date2 = dbo.__CorrectDate(#date2, 0)
IF (#date1 >= #date2)
SET #retValue = 0
ELSE BEGIN
DECLARE #days INT, #weekday INT
SET #days = DATEDIFF(d, #date1, #date2)
SET #weekday = DATEPART(dw, #date1) - 1
SET #retValue = DATEDIFF(s, #date1, #date2) - 2 * 24 * 3600 * ((#days + #weekday) / 7)
END
RETURN #retValue
END
GO
CREATE FUNCTION [dbo].[__CorrectDate](
#date DATETIME,
#forward INT
)
RETURNS DATETIME AS BEGIN
IF (DATEPART(dw, #date) > 5) BEGIN
IF (#forward = 1) BEGIN
SET #date = #date + (8 - DATEPART(dw, #date))
SET #date = DateAdd(Hour, (8 - DatePart(Hour, #date)), #date)
END ELSE BEGIN
SET #date = #date - (DATEPART(dw, #date)- 5)
SET #date = DateAdd(Hour, (18 - DatePart(Hour, #date)), #date)
END
SET #date = DateAdd(Minute, -DatePart(Minute, #date), #date)
SET #date = DateAdd(Second, -DatePart(Second, #date), #date)
END
RETURN #date
END
Here's a sql-fiddle demo for all non-weekend days in april (22).
SELECT [no weekend days in april] =
(dbo.DateDiff_NoWeekends('2013-04-01','2013-05-01')
/ 3600 / 24)
The query below gives the difference for week days alone , Ie counts the no od days between two days and subtracts the no of weekend days ,
DECLARE #StartDate DATETIME,
#EndDate DATETIME
SELECT #StartDate = '01-July-2008',
#EndDate = '30-July-2008'
;WITH DATE (Date1)
AS (
SELECT DATEADD(DAY, DATEDIFF(DAY, '19000101', #StartDate), '19000101')
UNION ALL
SELECT DATEADD(DAY, 1, Date1)
FROM DATE
WHERE Date1 < #EndDate
)
SELECT count(*) -
(
SELECT count(*)
--CONVERT(VARCHAR(15),d1.DATE1 ,110) as [Working Date],
--DATENAME(weekday, d1.Date1) [Working Day]
from DATE d1 where (DATENAME(weekday, d1.Date1)) in ('Saturday','Sunday')
)
--CONVERT(VARCHAR(15),d1.DATE1 ,110) as [Working Date],
--DATENAME(weekday, d1.Date1) [Working Day]
from DATE d1 where (DATENAME(weekday, d1.Date1)) not in ('Saturday','Sunday')
please let me know for any clarifications
Maybe I am still missing some full testing, but this works for me too: take the difference in days and then subtract 2 days for each weekend
DateDiff(d, d1, d2) - 2*DateDiff(wk, d1, d2)
Could be put in a function as well