Raise Error/ Throw Exception for Certain Condition SQL Server - sql

http://www.sqlfiddle.com/#!18/c913b/1
CREATE TABLE Table1 (
[ID] int PRIMARY KEY,
[Date] date,
[Name] varchar(40)
);
INSERT INTO Table1 (ID, date, Name )
Values ('1','07-20-18','Fred'),
('2','07-15-18','Sam'),
('3','07-20-18','Ben'),
('4','07-19-18','Simon'),
('5','07-25-18','Dave');
Current Query:
DECLARE #StartDate AS DATETIME,
#CurrentDate AS DATETIME
SET #StartDate = GETDATE() -30
SET #CurrentDate = GETDATE()
SELECT [ID], [Date], [Name]
FROM Table1
WHERE [Date] BETWEEN #StartDate AND #CurrentDate
Current result:
| ID | Date | Name |
|----|------------|-------|
| 1 | 2018-07-20 | Fred |
| 2 | 2018-07-15 | Sam |
| 3 | 2018-07-20 | Ben |
| 4 | 2018-07-19 | Simon |
This query compares with the range of day set for the #startdate variable. This can be changed to anything by anyone who wants to run the query. The issue is if someone selects a really large range of dates it crashes. Is there a way i can set an if statement that throws an error message if for example they tried to run a query for longer than 100 days.
Result: ERROR - Please lower the date range
Is this possible at all?

Related

Create work pattern SQL table

I'm looking to create what appears to be quite a simple table in SQL, however, I'm struggling to create it.
The first date at which the work pattern starts is 01/01/1990 (UK date format: dd/mm/yyyy - happy to have this as 1990/01/01 if necessary). The end date of the first period is 8 weeks from the start date (26/02/1990). The start date of the next period is the day after the previous end date (27/02/1990) and so on. I'd want the last end date to be some time in the future (at least 10 years from now).
This is ideally how I want the table to look:
+--------+------------+------------+
| Period | Start Date | End Date |
+--------+------------+------------+
| 1 | 01/01/1990 | 26/02/1990 |
| 2 | 27/02/1990 | 24/04/1990 |
| 3 | 25/04/1990 | 20/06/1990 |
| 4 | 21/06/1990 | 16/08/1990 |
| 5 | 17/08/1990 | 12/10/1990 |
+--------+------------+------------+
Any help much appreciated.
If you are just adding 8 weeks and not considering the weekends you can follow something like this.
DECLARE #tempTable TABLE(
Period INT IDENTITY PRIMARY KEY,
StartDate DateTime,
EndDate DateTime
);
DECLARE #startDate DATETIME = GETDATE();
DECLARE #endDate DATETIME;
DECLARE #currYear INT = DATEPART(YY,#startDate);
DECLARE #endYear INT = #currYear + 10;
WHILE (#currYear <= #endYear)
BEGIN
SET #endDate = DATEADD(WEEK,8,#startDate);
INSERT INTO #tempTable (StartDate, EndDate) VALUES(#startDate, #endDate);
SET #startDate = DATEADD(dd,1,#endDate);
SET #currYear = DATEPART(YY,#startDate);
END;
SELECT Period, FORMAT(StartDate,'dd/MM/yyyy') AS StartDate, FORMAT(EndDate,'dd/MM/yyyy') AS EndDate FROM #tempTable
CREATE TABLE your_table
(
Period INT,
StartDate DATE,
EndDate DATE
)
INSERT INTO your_table
VALUES
(1,'1990-01-01','1990-02-26')
--etc

Discard existing dates that are included in the result, SQL Server

In my database I have a Reservation table and it has three columns Initial Day, Last Day and the House Id.
I want to count the total days and omit those who are repeated, for example:
+-------------+------------+------------+
| | Results | |
+-------------+------------+------------+
| House Id | InitialDay | LastDay |
+-------------+------------+------------+
| 1 | 2017-09-18 | 2017-09-20 |
| 1 | 2017-09-18 | 2017-09-22 |
| 19 | 2017-09-18 | 2017-09-22 |
| 20 | 2017-09-18 | 2017-09-22 |
+-------------+------------+------------+
If you noticed the House Id with the number 1 has two rows, and each row has dates but the first row is in the interval of dates of the second row. In total the number of days should be 5 because the first shouldn't be counted as those days already exist in the second.
The reason why this is happening is that each house has two rooms, and different persons can stay in that house on the same dates.
My question is: how can I omit those cases, and only count the real days the house was occupied?
In your are using SQL Server 2012 or higher you can use LAG() to get the previous final date and adjust the initial date:
with ReservationAdjusted as (
select *,
lag(LastDay) over(partition by HouseID order by InitialDay, LastDay) as PreviousLast
from Reservation
)
select HouseId,
sum(case when PreviousLast>LastDay then 0 -- fully contained in the previous reservation
when PreviousLast>=InitialDay then datediff(day,PreviousLast,LastDay) -- overlap
else datediff(day,InitialDay,LastDay)+1 -- no overlap
end) as Days
from ReservationAdjusted
group by HouseId
The cases are:
The reservation is fully included in the previous reservation: we only need to compare end dates because the previous row is obtained ordering by InitialDay, LastDay, so the previous start date is always minor or equal than the current start date.
The current reservation overlaps with the previous: in this case we adjust the start and don't add 1 (the initial day is already counted), this case include when the previous end is equal to the current start (is a one day overlap).
There is no overlap: we just calculate the difference and add 1 to count also the initial day.
Note that we don't need extra condition for the reservation of a HouseID because by default the LAG() function returns NULL when there isn't a previous row, and comparisons with null always are false.
Sample input and output:
| HouseId | InitialDay | LastDay |
|---------|------------|------------|
| 1 | 2017-09-18 | 2017-09-20 |
| 1 | 2017-09-18 | 2017-09-22 |
| 1 | 2017-09-21 | 2017-09-22 |
| 19 | 2017-09-18 | 2017-09-27 |
| 19 | 2017-09-24 | 2017-09-26 |
| 19 | 2017-09-29 | 2017-09-30 |
| 20 | 2017-09-19 | 2017-09-22 |
| 20 | 2017-09-22 | 2017-09-26 |
| 20 | 2017-09-24 | 2017-09-27 |
| HouseId | Days |
|---------|------|
| 1 | 5 |
| 19 | 12 |
| 20 | 9 |
select house_id,min(initialDay),max(LastDay)
group by houseId
If I understood correctly!
Try out and let me know how it works out for you.
Ted.
While thinking through your question I came across the wonder that is the idea of a Calendar table. You'd use this code to create one, with whatever range of dates your want for your calendar. Code is from http://blog.jontav.com/post/9380766884/calendar-tables-are-incredibly-useful-in-sql
declare #start_dt as date = '1/1/2010';
declare #end_dt as date = '1/1/2020';
declare #dates as table (
date_id date primary key,
date_year smallint,
date_month tinyint,
date_day tinyint,
weekday_id tinyint,
weekday_nm varchar(10),
month_nm varchar(10),
day_of_year smallint,
quarter_id tinyint,
first_day_of_month date,
last_day_of_month date,
start_dts datetime,
end_dts datetime
)
while #start_dt < #end_dt
begin
insert into #dates(
date_id, date_year, date_month, date_day,
weekday_id, weekday_nm, month_nm, day_of_year, quarter_id,
first_day_of_month, last_day_of_month,
start_dts, end_dts
)
values(
#start_dt, year(#start_dt), month(#start_dt), day(#start_dt),
datepart(weekday, #start_dt), datename(weekday, #start_dt), datename(month, #start_dt), datepart(dayofyear, #start_dt), datepart(quarter, #start_dt),
dateadd(day,-(day(#start_dt)-1),#start_dt), dateadd(day,-(day(dateadd(month,1,#start_dt))),dateadd(month,1,#start_dt)),
cast(#start_dt as datetime), dateadd(second,-1,cast(dateadd(day, 1, #start_dt) as datetime))
)
set #start_dt = dateadd(day, 1, #start_dt)
end
select *
into Calendar
from #dates
Once you have a calendar table your query is as simple as:
select distinct t.House_id, c.date_id
from Reservation as r
inner join Calendar as c
on
c.date_id >= r.InitialDay
and c.date_id <= r.LastDay
Which gives you a row for each unique day each room was occupied. If you need a sum of how many days each room was occupied it becomes:
select a.House_id, count(a.House_id) as Days_occupied
from
(select distinct t.House_id, c.date_id
from so_test as t
inner join Calendar as c
on
c.date_id >= t.InitialDay
and c.date_id <= t.LastDay) as a
group by a.House_id
Create a table of all the possible dates and then join it to the Reservations table so that you have a list of all days between InitialDay and LastDay. Like this:
DECLARE #i date
DECLARE #last date
CREATE TABLE #temp (Date date)
SELECT #i = MIN(Date) FROM Reservations
SELECT #last = MAX(Date) FROM Reservations
WHILE #i <= #last
BEGIN
INSERT INTO #temp VALUES(#i)
SET #i = DATEADD(day, 1, #i)
END
SELECT HouseID, COUNT(*) FROM
(
SELECT DISTINCT HouseID, Date FROM Reservation
LEFT JOIN #temp
ON Reservation.InitialDay <= #temp.Date
AND Reservation.LastDay >= #temp.Date
) AS a
GROUP BY HouseID
DROP TABLE #temp

MSSQL Check If From, To Date will fit between time range

I need a function in MSSQL Server which as parameters will get #startTime #endTime and will check table reservation (which also has startTime and endTime) if asked date range will fit between time range within table and Return 1 If Yes and 0 If no. A little bit confusing I will explain better on table (At least I hope so)
I have table:
|:-----------------------|----------------------:|
| startDate | endDate |
|:-----------------------|----------------------:|
| 2017-01-25 00:00:00.000|2017-01-25 12:00:00.000|
| 2017-01-25 13:00:00.000|2017-01-25 14:00:00.000|
|:-----------------------|----------------------:|
Need to check If reservation will be avaible for i.e:
#startTime = 2017-01-25 13:30:00.000
#endTime = 2017-01-25 15:00:00.000
And should return 0 because there is reservation in this period of time.
I've tried do this by #startTime > startDate and #endTime < endDate but condition is check for every row and I need check whole table.
Kind Regards
You can do something like this:
select (case when exists (select 1
from reservations r
where r.startDate <= #endTime and
r.endDate >= #startTime
)
then 0 else 1
end) as available;
The logic is simple. Two time periods overlap if the first starts before the second ends and the first ends after the second starts.
create table info(startdate datetime, enddate datetime);
insert into info values
('2017-01-01', '2017-01-05'),
('2017-01-03', '2017-01-06'),
('2017-01-01', '2017-01-15'),
('2017-01-02', '2017-01-13'),
('2017-01-12', '2017-01-18');
declare #StartDate datetime = '2017-01-03';
declare #EndDate datetime = '2017-01-04'
select *
from info
where startdate <= #StartDate and enddate >= #EndDate;
+----+---------------------+---------------------+
| | startdate | enddate |
+----+---------------------+---------------------+
| 1 | 01.01.2017 00:00:00 | 05.01.2017 00:00:00 |
+----+---------------------+---------------------+
| 2 | 03.01.2017 00:00:00 | 06.01.2017 00:00:00 |
+----+---------------------+---------------------+
| 3 | 01.01.2017 00:00:00 | 15.01.2017 00:00:00 |
+----+---------------------+---------------------+
| 4 | 02.01.2017 00:00:00 | 13.01.2017 00:00:00 |
+----+---------------------+---------------------+

ExactTarget -SFMC SQL Query to Add Days

Running a query to send email subscribers a +X day email. FIRST_PROMO_SUBSCRIBE_DATE is coming from Oracle which they say is not a compatible format from Salesforce SQL so I have;
select * from PROMO_SUBSCRIBERS
where
(ORDER_ENGAGEMENT_LAST_DT > dateadd(day,-335,CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
or ORDER_ENGAGEMENT_LAST_DT is null)
and
(ORDER_LAST_DT > dateadd(day,-1,CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
or order_last_dt is null)
Are the parentheses correct?
You should just be able to cast the Oracle dates to date. Casting to date will also strip the time portion off of the datetime fields in T-SQL.
SQL Fiddle
MS SQL Server 2008 Schema Setup:
CREATE TABLE promo_subscribers
(
emailaddress varchar(255)
, ORDER_ENGAGEMENT_LAST_DT varchar(15)
, ORDER_LAST_DT varchar(15)
);
INSERT INTO promo_subscribers
(emailaddress, ORDER_ENGAGEMENT_LAST_DT, ORDER_LAST_DT)
VALUES
('test#example.com', '01-APR-98', '01-APR-16'),
('test#example.com', '01-MAY-98', '06-APR-16')
Query 1:
select
emailaddress
, order_engagement_last_dt
, cast(order_engagement_last_dt as date) datecast1
, order_last_dt
, cast(order_last_dt as date) datecast2
, dateadd(day,-335, cast(getDate() as date)) datecast3
, dateadd(day,-1, cast(getDate() as date)) datecast4
from PROMO_SUBSCRIBERS
Results:
| emailaddress | order_engagement_last_dt | datecast1 | order_last_dt | datecast2 | datecast3 | datecast4 |
|------------------|--------------------------|------------|---------------|------------|------------|------------|
| test#example.com | 01-APR-98 | 1998-04-01 | 01-APR-16 | 2016-04-01 | 2015-05-08 | 2016-04-06 |
| test#example.com | 01-MAY-98 | 1998-05-01 | 06-APR-16 | 2016-04-06 | 2015-05-08 | 2016-04-06 |

SQL Server 2008 R2 - Select Case When date between dates

I have a table Like this :
---------------------------------------------------------------
| UserID | Amount | PayDate |TransactionType| ...
----------------------------------------------------------------
| 1 | 140 | 2014-09-30 22:00:00.000| 7 |
| 2 | 230 | 2014-09-30 22:00:00.000| 7 |
| 1 | 120 | 2014-08-01 22:00:00.000| 7 |
| 2 | 135 | 2014-07-30 22:00:00.000| 7 |
| 1 | 120 | 2014-09-30 22:00:00.000| 4 |
----------------------------------------------------------------
I wrote the below query but it returns NULL, Please advise on this query as is:
The declared below dates are between 29/09/2014 and 1/10/2014
Declare
#dateStart datetime= CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(GETUTCDATE())+2),GETUTCDATE()),101),
#dateEnd datetime=(CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(GETUTCDATE())-1),GETUTCDATE()),101))
Select
MemberID,
case
when transactionType = 7
and (PayDate between #dateStart and #dateEnd) then Amount
End AS 'Outstanding Amount'
from
MemberPayment
My output should be :
| MemberID | OutStanding Amount|
---------------------------------
| 1 | 140 |
| 2 | 230 |
but the query returns null, what am I doing wrong ? Is the CASE When DATE between DATES used correct in SQL Server 2008 R2 ?
PS: Please note I do not want to change the query to have WHERE Condition.
Thank you in advance stack overflow family.
This should do the work
Declare
#dateStart datetime= DATEADD(dd,-(DAY(GETUTCDATE())+2),GETUTCDATE()),
#dateEnd datetime=DATEADD(dd,-(DAY(GETUTCDATE())-1),GETUTCDATE())
select MemberID, [Outstanding Amount]
from
(
Select
UserID as MemberID,
case
when transactionType = 7
and (PayDate between #dateStart and #dateEnd) then Amount
End AS 'Outstanding Amount'
from
MemberPayment
) As TmpQuery
where [Outstanding Amount] is not null
I removed the convert to varchar from both of your variables.
Then i put a select around your query, to filter just the results with Oustanding Amount not NULL.
Please take note, that I selected UserID as MemberID, because u used UserID in your example.
I tested it with a table, where PayDate is a Datetime Column.
As already mentioned in one of your comments i would prefer the easy method (and it`s much faster!):
Declare
#dateStart datetime= DATEADD(dd,-(DAY(GETUTCDATE())+2),GETUTCDATE()),
#dateEnd datetime=DATEADD(dd,-(DAY(GETUTCDATE())-1),GETUTCDATE())
select UserID, Amount as [Outstanding Amount]
from MemberPayment
where TransactionType = '7'
and PayDate between #dateStart and #dateEnd