Condition to COMPARE TWO DATE From parameter and ADD if it Satisfies - sql-server

This is MY procedure , Im getting from and to date in the procedure
i have to check if difference between FROM and TO date is greater than 2
if the condition satisfies i have to add 2days in from days and set it as TODATE
ALTER PROCEDURE [dbo].[sp_TU_AvgStdDev_Report]
#FromDate as Datetime,
#ToDate as Datetime,
#RecipeCode as Varchar(8000),
#Grade as Varchar(10),
#WcID as Int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
SET NOCOUNT ON;
IF (condition to check if #FromDate - #ToDate > 2)
--if it satisfies
SET #ToDate to #fromDate+2Days
Please help me in figuring it out...

You need to used date functions for this.
ALTER PROCEDURE [dbo].[sp_TU_AvgStdDev_Report]
#FromDate as Datetime,
#ToDate as Datetime,
#RecipeCode as Varchar(8000),
#Grade as Varchar(10),
#WcID as Int
AS
BEGIN
IF (datediff(day,#FromDate,#ToDate)>2)
SET #ToDate = DATEADD(day,2, #fromDate)

Use DATEDIFF and DATEADD Function
IF DATEDIFF(D,#FromDate,#ToDate) > 2
BEGIN
--if it satisfies
SET #ToDate = DATEADD(D,2, #fromDate)
END

You should have to use DateDiff
Use below query may be it helps you.
if( Datediff(day, Todate, FromDate) > 2)
// Your query

First remove the time part from date by converting it to date like
convert(date,convert(varchar,#FromDate))
convert(date,convert(varchar,#ToDate))
So then you will have only date and then you can find the difference between two date using DATEDIFF sql function
Final solution
IF DATEDIFF(day,convert(date,convert(varchar,#FromDate)),convert(date,convert(varchar,#ToDate))) > 2
BEGIN
--if it satisfies
SET #ToDate = DATEADD(day,2, convert(date,convert(varchar,#FromDate)))
END

Related

SQL query accepting date parameter in MM-DD-YYYY format instead of DD-MM-YYYY

Here is my stored procedure which accepts two date parameters, one for start date and second for end date. It gets a bunch of different data from joined tables:
#FromDate varchar(50),
#ToDate varchar (50)
SELECT DISTINCT
dbo.DefectInspection.DefectInspection_Id,
CONVERT(varchar(50), CAST(dbo.DefectInspection.DefectInspection_CreatedDate AS date), 34) AS CreatedDate
FROM
(bunch of tables)
WHERE
CAST(DefectInspection.DefectInspection_CreatedDate AS date)
BETWEEN CAST( #FromDate AS Date) AND CAST(#ToDate AS Date)
The issue is it will only return date if I input my dates as MM-DD-YYYY instead of the days firsts. This is an issue because the date style sent from client side is always DD-MM-YYYY
Using desired input: no data returedn
Using month format - data returned
When using SQL (and other languages) its best to use an unambiguous format such as yyyy-mm-dd
Also consider using the DATE type instead of VARCHAR
#FromDate DATE(50),
#ToDate DATE(50)
Though using the wrong datatypes is terrible, sometimes we all have to deal with issues which cannot be changed easily.
You can use:
DECLARE #fromDate AS varchar(50);
DECLARE #toDate AS varchar(50);
DECLARE #from AS date;
DECLARE #until AS date;
SET #fromDate = '09-01-2023';
SET #toDate = '10-01-2023';
SET #from = TRY_CONVERT(date, #fromDate, 105);
SET #until = TRY_CONVERT(date, #toDate, 105);
IF #from IS NULL OR #until IS NULL
THROW 51000, 'Parameter is not a valid date ..', 0;
ELSE BEGIN
SELECT DISTINCT
...
FROM
(bunch of tables)
WHERE TRY_CONVERT(date, DefectInspection.DefectInspection_CreatedDate, 110) BETWEEN #from AND #until;
END;
TRY_CONVERT returns NULL if the parsing fails.
The 3rd parameter (style) 105 means format "dd-mm-yyyy" like you use it, 110 means "mm-dd-yyyy".

SQL Server : Table valued function returning dates for last 10 days from today

I am new to SQL Server and am trying to write a table valued function that returns dates for the last 10 days from the current date. How do I do this?
Maybe this will take you a step closer. You can use below code to get last 10 dates + today.
Tweak this and push this into a function.
SELECT
date = DATEADD(d,-1* days,CAST(GETDATE() AS DATE))
FROM
(
VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)
)V(days)
First create a procedure that finds the last 10 days for a given input date like this:
CREATE PROCEDURE dbo.getLast10Days(#inputDate DATETIME)
AS BEGIN
DECLARE #count INT;
SET #count = 1;
WHILE #count <= 10
BEGIN
PRINT DATEADD(DAY, - #count, #inputDate)
SET #count = #count + 1
END
END
GO
In order to execute this procedure for the current date, this will do:
DECLARE #currentDate DATETIME
SET #currentDate = GETDATE()
EXEC dbo.getLast10Days #inputDate = #currentDate
If you don't want to use the current date as getdate(), but to use a date from a table, just do something like this:
DECLARE #currentDate DATETIME
SET #currentDate = SELECT theDateColumn FROM yourTable
EXEC dbo.getLast10Days #inputDate = #currentDate

How to store the result of each iteration of a cycle? (SQL Server)

I'm making a stored procedure, the purpose is to produce a Forecast for maintenance schedule, it so that when I give it a range of dates and amount of days, it would give me a set of results displaying the different dates that fall under that criteria.
I have been trying with a while loop, but I have not been able to get more than 1 result, I only get the last possible result of the range.
ALTER PROCEDURE [dbo].[ApruebaFecha](
-- Add the parameters for the stored procedure here
#LastDate DATETIME, -- Last Scheduled Date (Range Start)
#Setting1 INT, -- Length of Period
#FechaHasta datetime, -- End of Range
#Result DATETIME OUTPUT)
AS
BEGIN
/* Today */
DECLARE
#TodaysDate DATETIME
SELECT #TodaysDate = CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 101), 101)
SELECT convert(datetime, CONVERT(varchar,#FechaHasta,101),101 )
-- Finding today's date after resetting the time to midnight
/* Schedule Date */
DECLARE
#ScheduleDate DATETIME
-- Find the starting schedule date. If the schedule date is in a previous
-- month, adjust to the current month
-- Adjust the days
SELECT #ScheduleDate = #LastDate
WHILE (#ScheduleDate < #TodaysDate AND #TodaysDate <#FechaHasta)
SELECT #ScheduleDate = DATEADD(day, #Setting1, #ScheduleDate)
IF (#ScheduleDate = #LastDate)
SELECT #ScheduleDate = DATEADD(day, #Setting1, #ScheduleDate)
SELECT #Result = #ScheduleDate
WHILE(#Result <#FechaHasta)
BEGIN
IF(#Result <#FechaHasta)
SELECT #Result = DATEADD(day, #Setting1, #Result)
SET IDENTITY_INSERT [00TblFecha] ON
INSERT INTO dbo.[00TblFecha](idFecha,jobno,fecha)VALUES('','',#Result)
SET IDENTITY_INSERT[00TblFecha] OFF
print #Result
end
END -- GetScheduleDate_Daily_PeriodicDay
the result that you see is from this statement at line 5:
SELECT convert(datetime, CONVERT(varchar,#FechaHasta,101),101 )
you should put a statement at the end of your stored procedure like this :
select idFecha,jobno,fecha
from dbo.[00TblFecha]

How to subtract two date as datetime2 format in Sql Server 2008

How can I create a method to subtract two dates and this is equal to in real date as format datetime2(7) in sql server 2008.
For example ,I create this method:
Delete from TblMessage
Where MDateTime<((SELECT TOP (1)MDateTime FROM TblMessage ORDER BY MDateTime DESC)- ('2013-10-04 16:47:56.0000000'))
but it is not working .I want to result of subtract two date like this:
MDateTime1:2013-10-05 16:47:56.0000000
MDateTime2:2013-09-04 16:47:56.0000000
Result:2013-01-01 00:00:00.0000000
Result=MDateTime1-MDateTime2
How can I do this. Thanks...
Perhaps you are looking for this?
select DATEADD( day, datediff(day,GETDATE(), getdate() - 10), GETDATE() ) ;
DATEDIFF(dayofyear,MDateTime1,MDateTime2) AS Result
http://msdn.microsoft.com/en-us/library/ms189794.aspx
DECLARE
#DATE1 DATETIME = '2013-10-05 16:47:56.000',
#DATE2 DATETIME = '2013-09-04 17:37:42.000',
#DATEDIFF AS INT,
#BASEDATE DATETIME;
-- USE WHAT EVER DATE YOU WISH TO BE YOUR BASE DATE
SET #BASEDATE = '1/1/1900';
SET #DATEDIFF = DATEDIFF(SECOND, #DATE2, #DATE1);
SELECT #DATE1,#DATE2,#DATEDIFF, DATEADD(SECOND,#DATEDIFF,#BASEDATE)
Thus a scalar function could be created like this...
CREATE FUNCTION dbo.sf_GetMeasureDate
(
#EndDate DATETIME,
#StartDate DATETIME,
#BaseDate DATETIME
)
RETURNS DATETIME
AS
BEGIN
DECLARE #DATEDIFF AS INT
SET #DATEDIFF = DATEDIFF(SECOND, #StartDate, #EndDate);
Return DATEADD(SECOND,#DATEDIFF,#BASEDATE)
END
GO
Then within you regular SELECT statement you can call the function as such.
SELECT dbo.sf_GetMeasureDate('2013-10-05 16:47:56.000','2013-09-04 17:37:42.000','1/1/1900')
or within an existing query:
SELECT dbo.sf_GetMeasureDate([fld1],[fld2],'1/1/1900')

Check Constraint not firing correctly

I'm pretty sure I am doing something wrong, as this is my first check constraint, but I can't understand why it's not working. I need to check that a date range doesn't overlap.
ALTER FUNCTION fn_DateOverlaps (#StartDate DATE, #EndDate DATE, #ProjectID INT)
RETURNS BIT
AS
BEGIN
DECLARE #Ret BIT
SET #Ret = 1
IF NOT EXISTS(
SELECT * FROM project_sprint
WHERE ((#StartDate >= StartDate AND #EndDate <= EndDate)
OR (#StartDate <= StartDate AND #EndDate >= EndDate))
AND ProjectId = #ProjectId
)
BEGIN
SET #Ret = 0
END
RETURN #Ret
END
GO
I then apply this to my table:
ALTER TABLE Project_Sprint WITH CHECK ADD CONSTRAINT ck_DateOverlaps CHECK (dbo.fn_DateOverlaps([StartDate], [EndDate], [ProjectId])=1)
GO
When I test the function, I get a good result:
SELECT dbo.fn_DateOverlaps('2013-06-10', '2013-06-13', 1)
But then when I apply the same date range and project ID to my table, it allows the insert. It should fail it.
What am I doing wrong?
If you change SELECT * FROM project_sprint to SELECT * FROM dbo.project_sprint the function will correctly evaluate, but you won't get the desired behavior, since the value you are inserting or editing will lead to an unwanted find.
To prevent this you will have to add an additional ID field to except the row you want to edit/insert for the check.
Create Table Project_Sprint(ID int IDENTITY(1,1) NOT NULL,ProjectID int,StartDate DateTime,EndDate DateTime)
go
Alter FUNCTION fn_DateOverlaps (#ID int,#StartDate DATE, #EndDate DATE, #ProjectID INT)
RETURNS BIT
AS
BEGIN
DECLARE #Ret BIT
SET #Ret = 0
IF NOT EXISTS(
SELECT * FROM dbo.project_sprint
WHERE
#ID<>ID AND
((#StartDate >= StartDate AND #EndDate <= EndDate)
OR (#StartDate <= StartDate AND #EndDate >= EndDate))
AND ProjectId = #ProjectId
)
BEGIN
SET #Ret = 1
END
RETURN #Ret
END
GO
ALTER TABLE Project_Sprint ADD CONSTRAINT ck_DateOverlaps CHECK (dbo.fn_DateOverlaps([ID],[StartDate], [EndDate], [ProjectId])=1)

Resources