To add five business days to a date in SQL Server, you can use a query that takes into account weekends (typically Saturday and Sunday) as non-working days. Here's a SQL query that demonstrates how to add five business days to a given date:
```
DECLARE @StartDate DATETIME = '2023-09-16'; -- Replace with your desired start date
-- Calculate the end date with five business days added
DECLARE @EndDate DATETIME = @StartDate;
-- Loop to add five business days
DECLARE @BusinessDaysToAdd INT = 5;
WHILE @BusinessDaysToAdd > 0
BEGIN
-- Add one day to the current date
SET @EndDate = DATEADD(DAY, 1, @EndDate);
-- Check if the current day is a weekend (Saturday or Sunday)
IF DATENAME(WEEKDAY, @EndDate) NOT IN ('Saturday', 'Sunday')
BEGIN
-- If it's not a weekend, decrement the remaining business days to add
SET @BusinessDaysToAdd = @BusinessDaysToAdd - 1;
END
END
-- Output the result
SELECT @StartDate AS StartDate, @EndDate AS EndDate;
```
In this query:
1. Replace `@StartDate` with your desired starting date.
2. The query initializes `@EndDate` with the start date and then enters a loop.
3. Inside the loop, it adds one day to `@EndDate` in each iteration.
4. It checks whether the current day (after adding one day) is a weekend (Saturday or Sunday). If it's a weekend, it doesn't decrement the `@BusinessDaysToAdd` counter.
5. If the current day is not a weekend, it decrements the `@BusinessDaysToAdd` counter.
6. The loop continues until `@BusinessDaysToAdd` becomes zero, at which point you have the end date with five business days added.
Finally, the query selects both the start date and the calculated end date.
No comments:
Post a Comment