Add 30 calendar dates to a date column - sql-server

Hope you are doing well.
I use Microsoft SQL server Mgt studios 18.
I have a table which has a Date column to which i need to add 30 working days (holidays are not considered, have to exclude only Saturday and Sunday) and have the resulted date in another column named altered Date in the same table.
I am going to use the script/query as a trigger on update. So i cannot create and use function.
Is there any other simple way that i can do this?
Appreciate your inputs.

So this is a simple way to insert dates into a table and skip Saturday's and Sundays. If you need it to start at a specific day, you can simply add a parameter in place of GETDATE(); If you need additional help, comment and I can edit this answer.
CREATE TABLE YOURTABLENAME (
MyDate Date
);
DECLARE #i int;
SET #i = 0
WHILE #i < 30
begin
SET #i = #i + 1;
IF DATEPART(WEEKDAY, DATEADD(day, #i, GETDATE())) BETWEEN 2 and 6
BEGIN
INSERT INTO YOURTABLENAME VALUES(DATEADD(day, #i, GETDATE()))
END
END
SELECT * FROM YOURTABLENAME

Related

Select date individually from list of dates

ALTER PROCEDURE [dbo].[spGetData]
#startdate DATE
AS
WITH dates(Date) AS
(
SELECT #startdate AS Date
UNION ALL
SELECT DATEADD (d, 1, [Date])
FROM dates
WHERE DATE < GETDATE()
)
SELECT Date
FROM dates
OPTION (MAXRECURSION 0)
GO
it returns a list of dates
exec spGetData #startdate = '2019/11/28'
Output:
Date
----------
2019-11-28
2019-11-29
2019-11-30
2019-12-01
2019-12-02
2019-12-03
How do I select each date individually in the same stored procedure as I want to pass date as parameter in another stored procedure?
All you need to do is ditch all the current code and put a WHILE loop that starts with the current date and increments it with DATEADD each time.
I'm presuming you have a reason that the other SP needs to be called separately for each date.
First define a table type like :
CREATE TYPE UT_Date AS TABLE
(
startdate date
)
You can use this to pass multiple records in Stored procedure as parameter like:
CREATE PROCEDURE USP_OtherSP(#Dates [UT_Date])
AS
BEGIN
--you can access table valued parameter data just like a table
SELECT * FROM #Dates
-- your logic here
END

T-SQL: select date range from last Friday at 1230pm until Monday at 330am

I'm creating a query in SQL Server 2008, for an SSRS report that runs every Monday at 0330am, retrieving weekend sales details.
The report is ready, but I had to hard-code the date range, as I'm having trouble expressing that condition in the WHERE statement.
I need to retrieve data based on column [salestime] (of type datetime), between Friday at 1230pm and Monday at 330am.
I'd really appreciate your assistance with this.
How about something like:
WHERE SalesTime BETWEEN DATEADD(HH,-63,GETDATE()) AND GETDATE()
I believe the time values are 63 hours apart. This is if your report automatically runs at 3:30 AM, which is what it sounds like in your post.
If you want to run your report any time during the week to report on last weekend's sale
SET DATEFIRST 7
DECLARE #ThisMonday date = DATEADD(DAY, 2 - DATEPART(WEEKDAY, GETDATE()), GETDATE())
DECLARE #LastFriday date = DATEADD(DAY, -3, #ThisMonday)
DECLARE #StartTime datetime = CAST(#LastFriday AS datetime) + CAST('12:30' AS datetime)
DECLARE #EndTime datetime = CAST(#ThisMonday AS datetime) + CAST('03:30' AS datetime)
SELECT #ThisMonday, #LastFriday, #StartTime, #EndTime
Now you can filter your report with salestime BETWEEN #StartTime AND #EndTime.

SQL Data not showing data for certain date ranges

I am having some issues with getting dates showing up in my query when I changed the dates in my variable, below is what I have declared.
declare #record int;
declare #start_date date;
declare #end_date date;
set #record = 2;
set #start_date = '2016-03-01';
set #end_date = '2016-03-31';
What I have created is temp tables which populate my data by Date ranges. The dates are set up as below
- Daily 2016-01-15
- weekly 2016-51
- Monthly 2016-04
- Quarterly 2016-01
- Yearly 2016
So when I declare the dates above and filter by yearly I should get data back, in fact no matter what date I put in for yearly I should get results but nothing is showing up.
When I declare the start date = 2016-01-01 it returns data for everything I filter by.
Can anybody offer some advice on a way to fix this problem I have no idea.
I don't know what is your query which is not working, but the basic isead sould be like that:
select * from YourTempTable where datepart (yy, DateField) = datepart(yy, #start_date)
of course this is not optimal for big tables as it wouldn't use any index.
Better would be to construct a #DateFrom and #DateTo variables based on the period you are looking for and the reference dates described above and make your select accordingly:
select * from YourTempTable where DateField between = #DateFrom and #DateTo

TSQL Function to calculate 30 WORKING days Date from a Specified Date (SQL Server 2005)

TSQL Function to calculate 30 WORKING days Date from a Specified Date (SQL Server 2005)?
Input parameters would be Date and Number of Working Days.
Output would be the Calculated Date.
This would exclude Saturday, Sunday, Holidays and Day Holiday was observered.
i.e. If the Holiday falls on a weekend but it is observed on the Friday or Monday after the holiday.
For the Holidays we have a table with holiday and day it is being observed date.
Have a look at this article by Celko - in general you need to "pre-calculate" a calendar table to take in account all possible vagaries like Easter, bank holidays etc.
There's one right in the SQL online help if you scroll down to UDF to return the number of business days, including a check to a bank holidays table
you can tweak this.
Instead of writing a tsql function, it might easier if you build a table that's similar to the Date Dimension (DimDate) table in data warehouse. DimDate would contain a column named isHoliday. You can also add other columns that might be useful. Then you write a script to populate DimDate
Then you can run a query off it.
I don't have a table of holidays handy, so I haven't tested this very much - but as nobody else has attempted an answer, here's how I'd start:
declare #tempDate datetime,
#StartDate datetime,
#WorkingDays int,
#NonWorkingDays int,
#TargetDate datetime
set #StartDate = '2010-10-26' --Change this to a paramter
set #WorkingDays = 9 --Change this to a parameter
set #NonWorkingDays = -1
/*Work out the answer ignoring holidays */
set #tempDate = dateadd(d,#WorkingDays,#StartDate)
while (dateadd(d,#WorkingDays + #NonWorkingDays, #StartDate) < #tempDate)
begin
/*Work out how many holidays are in the interval we've worked out*/
select #NonWorkingDays = count(HolidayDate)
from Holidays
where HolidayDate between #StartDate and #tempDate;
/*Extend the interval to include the holidays we've just found*/
set #tempDate = dateadd(d,#NonWorkingDays,#tempDate)
/*See if #NonWorkingDays has changed with the new #tempDate*/
select #NonWorkingDays = count(HolidayDate)
from Holidays
where HolidayDate between #StartDate and #tempDate;
end
set #TargetDate = dateadd(d,#WorkingDays + #NonWorkingDays, #StartDate)
print 'Target Date: ' + cast(#TargetDate as varchar(50))
Note this only works for Holidays at the moment - not weekends. You'd have to load all weekends into the holiday table (or join to a weekends table or use the DATENAME function) but the calculation should be the same.
Not sure how your Holiday table handles duplicate dates (eg. Boxing Day and St Stephen's Day both fall on 26th Dec) so you might need to take account of that.

Ignoring the time element of a datetime field

I have a datetime field in my table. I want to delete records based on a date but I am not interested in the time element. How would I write the SQL for this ? I am using MS SQL 2008.
For best use of indexes, I'd go for this kind of approach:
To delete all records for 1st December:
DECLARE #DateToDelete DATETIME
SET #DateToDelete = '20091201'
DELETE FROM MyTable
WHERE MyDateField >= #DateToDelete AND MyDateField < DATEADD(dd, 1, #DateToDelete)
The alternatives include:
DELETE FROM MyTable
WHERE CAST(CONVERT(VARCHAR(10), MyDateField, 120) AS DATETIME) = #DateToDelete
which converts each datetime value to just it's date part.
But I'd still go with my original way as it allows for more efficient execution.
If you use MS SQL 2008 then you could convert to a new DATE type
DELETE FROM table WHERE date_filed >= CONVERT(DATE,GETDATE())
Is the time relevant in any other place? If not, then you should use a DATE column instead. If you cannot, then the best way to seek a date part of a datetime in a WHERE clause is to use a range:
... WHERE dateColumn BETWEEN '20091221' and '20091222';
Note that given the datetime accuracy of 3ms a datetime like 20091221 23:59:59.999 may be aproximated to 20091222 00:00:00.000 and this can sometime create problems.
There is a great collection of blog posts on the topic of datetime at T-SQL Tuesday #001 (Date/Time Tricks): The Roundup
Try this:-
declare #date datetime
set #date = '2006-11-09'
select #date, dateadd(ms, -1, DATEADD(dd,1,#date))
delete from login
where datecreated between #date AND dateadd(ms, -1, DATEADD(dd,1,#date))
This is what datediff is for:
delete from Table where datediff(day,'2009-12-09',date_filled) = 0

Resources