How to to pass a date to a stored procedure? - sql-server

I have the following SP:
IF EXISTS (SELECT * FROM [dbo].[Assignments]
WHERE ProjectId=#ProjectUID AND TaskId=#TaskUID AND ResourceId=#ResourceUID
AND (StartDate <= #DATE AND FinishDate >= #DATE)
)
BEGIN
Return 1
END
ELSE
BEGIN
Return 2
END
When I executed it with some parameters, it's returns me 2(I have taken this parameter for my date #Date = '2018-11-02') so I decided to try in select statement, and the select statement return me a line and if I put my Line with start and end date in comments, my SP works
So I know that my trouble is coming from the date
But I don't understand why
PS: I have already tried with a between but the result is the same

Compare dates using the date parts of datetime columns:
IF EXISTS (
SELECT *
FROM [dbo].[Assignments]
WHERE
ProjectId = #ProjectUID AND
TaskId = #TaskUID AND
ResourceId = #ResourceUID AND
(CONVERT(date, StartDate) <= #DATE AND CONVERT(date, FinishDate) >= #DATE)
)
BEGIN
Return 1
END
ELSE
BEGIN
Return 2
END

Related

find latest date between created date and updated date in sql stored procedure [duplicate]

This question already has answers here:
Selecting most recent date between two columns
(13 answers)
Closed 3 years ago.
I have two column in my table as created date and updated date.I want to find latest date from that.which ever is latest I want to considered that and filter it from input values.
My current query is :-
Select *
from Emp E
WHERE (E.USERID=#UserID) and (E.CDATE >= #FromDate AND E.CDATE <= #ToDate) order by qdate desc
You can subtract fromDate and toDate with system date to find the latest date. And by using case you can filter based on the latest date.
Like:
SELECT *
FROM Emp E
WHERE ( E.USERID = #UserID )
AND E.CDATE = CASE WHEN #fromdate - GETDATE() > #toDate - GETDATE()
THEN #fromdate
ELSE #toDate
END;
To find the latest date between two dates, you can use reference of the script below.
DECLARE #fromdate DATETIME, #toDate DATETIME, #date DATETIME
SET #fromdate = '2019-04-05'
SET #toDate = '2019-05-05'
SET #date = CASE WHEN #fromdate - GETDATE() > #toDate - GETDATE() THEN #fromdate
ELSE #toDate
END;
SELECT #date;
SELECT *
FROM Emp E
WHERE (E.USERID = #UserID)
AND 1 = CASE
WHEN E.CDATE >= E.UDATE
THEN CASE
WHEN (
E.CDATE >= #FromDate
AND E.CDATE <= #ToDate
)
THEN 1
END
WHEN E.CDATE < E.UDATE
THEN CASE
WHEN (
E.UDATE >= #FromDate
AND E.UDATE <= #ToDate
)
THEN 1
END
ELSE 0
END
assuming update date is UDATE
select *
from Emp E
where (E.USERID=#UserID)
and (SELECT MAX(V) from (values(E.CDATE), (E.UDATE)) MAX_DATE(V)) BETWEEN #FromDate AND #ToDate
declare #cdate smalldatetime,#udate smalldatetime
Select CDATE=max(CDATE ) ,UDATE =max(UDATE ) into #tbldate
from Emp
set #cdate =(select CDATE from #tbldate)
set #udate =(select udate from #tbldate)
if(#cdate>#udate)
begin
Select CDATE as Latest_Date from #tbldate
end
else
begin
Select UDATE as Latest_Date from #tbldate
end
//Run this by selecting all

Add Hours to Current Date But it excludes the holidays and weekends

I have a task to create the T-SQL function to add the 12 hours with current date and time but it should not include any holidays/weekends.
ALTER FUNCTION [dbo].[GetNextWorkingDay_Custom] (#givenDate DATETIME)
RETURNS DATE
AS
BEGIN
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
DECLARE #DiffDate INT
DECLARE #workingDate DATETIME
IF (DATENAME(dw , #givenDate) = 'Friday')
BEGIN
SET #workingDate = DATEADD(day, 3, #givenDate)
END
ELSE IF (DATENAME(dw , #givenDate) = 'Saturday')
BEGIN
SET #workingDate = DATEADD(day, 2, #givenDate)
END
ELSE
BEGIN
SET #workingDate = DATEADD(day, 1, #givenDate)
END
SELECT #StartDate = START_DATE
,#EndDate = END_DATE
FROM special_time WHERE START_DATE = #workingDate AND IS_HOLIDAY = 1
-- Select count(*) from tblHolidays where holdate = #workingDate
while ((select count(*) from special_time WHERE START_DATE = #workingDate AND IS_HOLIDAY = 1) > 0)
begin
set #DiffDate = DATEDIFF(day,#StartDate,#EndDate)
set #workingDate = dateadd(dd,#DiffDate,#WorkingDate)
end
-- if adding a day makes it a Saturday, add 2 more to get to Monday (and test to make sure the week doesn't start with a holiday)
IF (DATENAME(dw , #workingDate) = 'Saturday')
BEGIN
SET #workingDate = DATEADD(day, 2, #workingDate)
END
RETURN #workingDate
END
Create a static dates lookup table (you can find many guides on how to do this via google, such as https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/) and then add a column that signifies whether or not that date is a working day or a holiday.
Your function is then as simple as:
select min(DateValue) as NextWorkingDay
from DatesLookupTable
where DateValue > #GivenDate
and WorkingDay = 1

How to check if a month and year lies between 2 dates

I have a 2 columns in a table startdate and enddate and I need to create a function get all ID which lies between the date data passed in function.
my function input parameters are
#Year int,
#Month int = null,
#Quarter int = null
now if month is null I need to check only with date which is easy but if month is provided how to check if it lies between startdate and enddate or else if #Quarter is provided I need to check if 3 months of the year collides with startdate and enddate .
What I have written upto now is
CREATE FUNCTION GetAssociatesEmpID(
#Year int,
#Month int = null,
#Quarter int = null
)
RETURNS TABLE
AS BEGIN
IF #Month IS NOT NULL -- Monthly Statistics
BEGIN
END
ELSE IF #Quarter IS NOT NULL -- Quarterly Statistics
BEGIN
END
ELSE -- Yearly Statistics
BEGIN
return SELECT ID FROM Table WHRER #Year>=YEAR(startdate) AND #Year<=YEAR(enddate)
END
END
Kindly help me with condition with month and Quarter
Quarter has 4 possible inuts range between 1-4
and its month range is between #Quarter*3-3 and #Quarter*3
Start by creating two local DateTime variables. (Or DateTime2, or whatever data type your table's start and end date columns are using.) Maybe call them #WhereStartDate and #WhereEndDate.
Use some IF statements to populate your new #WherexxxDate variables. For example, if Month is provided, something like:
DECLARE #Year int = 2016;
DECLARE #Month int = 3;
DECLARE #WhereStartDate datetime;
DECLARE #WhereEndDate datetime;
SET #WhereStartDate = CONVERT( datetime, CAST(#Year as char(4)) + '/' + CAST(#Month as varchar(2)) + '/01');
SET #WhereEndDate = DATEADD( day, -1, DATEADD( month, 1, #WhereStartDate ));
SELECT #WhereStartDate, #WhereEndDate;
Once you have actual date/time variables, you can write your query appropriately...
SELECT ...
...
WHERE startDate >= #WhereStartDate
AND enddate <= #WhereEndDate
This has the added benefit of being sargable. The way that you have written your query is non-sargable. (In short, non-sargable queries will not make use of indexes properly and will have poor performance. If the table is large, the resulting table scans could take a very long time.)
Not where I can test, but this should be close...
WHERE
(#Year >= YEAR(startdate))
AND
(#Year <= YEAR(startdate))
AND
(
( (#Month IS NOT NULL) AND (#Month >= MONTH(startdate)) AND (#Month <= MONTH(startdate)) )
OR
( (#Month IS NULL) AND (#Quarter >= DATEPART(QUARTER, startdate)) AND (#Quarter <= DATEPART(QUARTER, startdate)) )
)

SQL server 2008 R2 Scalar function does not work

I have this function, which should bring me the end of month date of an invoice.
E.g. Invoice (ARID) have a created date 2015-09-1, the eom is 2015-09-30.
ALTER FUNCTION [dbo].[sfEOM](#ARID int, #Switch int)
RETURNS date
AS
BEGIN
declare #Letzter date
declare #MaxLeistungsdatum as date
if #Switch=1
set #Letzter = (select CONVERT(date, DATEADD(MONTH,DATEDIFF (MONTH,0,tblleistungen.LeistungsDatum),30),0) from dbo.tblleistungen where ARID=#ARID group by ARID,CONVERT(date, DATEADD(MONTH,DATEDIFF(MONTH,0,tblleistungen.LeistungsDatum),30),0) )
else
set #MaxLeistungsdatum=(select max(LeistungsDatum) from tblDatensaetzeBA where ARID=#ARID group by ARID)
set #Letzter = (select CONVERT(date, DATEADD(MONTH,DATEDIFF(MONTH,0,#MaxLeistungsdatum),30),0))
RETURN #Letzter
END
go
To use one function for two different tables I use as #Switch
but
select dbo.sfEOM(9307396,1)
or
select dbo.sfEOM(9307396,2)
brings NULL as result where as
select CONVERT(date, DATEADD(MONTH,DATEDIFF (MONTH,0,tblleistungen.LeistungsDatum),30),0) from dbo.tblleistungen where ARID9307396 group by ARID,CONVERT(date, DATEADD(MONTH,DATEDIFF(MONTH,0,tblleistungen.LeistungsDatum),30),0)
brings the correct date.
When I omit if #Switch=1 and have only
set #Letzter = (select CONVERT(date, DATEADD(MONTH,DATEDIFF (MONTH,0,tblleistungen.LeistungsDatum),30),0) from dbo.tblleistungen where ARID=#ARID group by ARID,CONVERT(date, DATEADD(MONTH,DATEDIFF(MONTH,0,tblleistungen.LeistungsDatum),30),0) )
it works too.
Whats wrong there?
Thanks!
Michael
You need to define the code blocks for the if statement:
ALTER FUNCTION [dbo].[sfEOM](#ARID int, #Switch int)
RETURNS date
AS
BEGIN
declare #Letzter date
declare #MaxLeistungsdatum as date
if #Switch = 1
begin
set #Letzter = (select CONVERT(date, DATEADD(MONTH,DATEDIFF (MONTH,0,tblleistungen.LeistungsDatum),30),0) from dbo.tblleistungen where ARID=#ARID group by ARID,CONVERT(date, DATEADD(MONTH,DATEDIFF(MONTH,0,tblleistungen.LeistungsDatum),30),0) )
end
else
begin
set #MaxLeistungsdatum=(select max(LeistungsDatum) from tblDatensaetzeBA where ARID=#ARID group by ARID)
set #Letzter = (select CONVERT(date, DATEADD(MONTH,DATEDIFF(MONTH,0,#MaxLeistungsdatum),30),0))
end
return #Letzter
end;
go

Get number of weekends between two dates in SQL

I need to get the number of weekends between dates in sql as a function. I have tried but stuck up somewhere in the logic.
CREATE FUNCTION fnc_NumberOfWeekEnds(#dFrom DATETIME, #dTo DATETIME)
RETURNS INT AS
BEGIN
Declare #weekends int
Set #weekends = 0
While #dFrom <= #dTo Begin
If ((datepart(dw, #dFrom) = 1))
Set #weekends = #weekends + 1
Set #dFrom = DateAdd(d, 1, #dFrom)
End
Return (#weekends)
END
I tried out this logic with several edge cases and it seems to work.
SELECT DATEDIFF(d, #dFrom, #dTo)/7+1
+ CASE WHEN DATEPART(dw,#dFrom) IN (1,7) THEN -1 ELSE 0 END
+ CASE WHEN DATEPART(dw,#dTo) IN (1,7) THEN -1 ELSE 0 END
You can change the CASE statements depending on how you want to handle cases where the start or end date is in a weekend. In my case I'm not including the weekend if the start or end date is a Saturday or Sunday.
Try replacing the if statement with this:
If ((datepart(dw, #dFrom) = 1) OR (datepart(dw, #dFrom) = 7))
You should also check the end of the week to get the result.
DECLARE #date_from DATETIME,
#date_to DATETIME
/*TEMPORARY TABLE*/
DECLARE #DATES AS TABLE (
GDate DATETIME
)
SELECT #date_from ='2019-09-10'
SELECT #date_to ='2019-10-10'
/*DATE GENERATED*/
WITH dates
AS (
SELECT #date_from AS dt
UNION ALL
SELECT DATEADD(D, 1, dt)
FROM dates
WHERE dt < #date_to
)
/*INSERTED DATES INTO TEMP TABLE */
INSERT INTO #DATES
SELECT CONVERT(DATETIME, dt) AS Gdate FROM dates
/*Get Records from temp table*/
SELECT Gdate FROM #DATES
Used below logic to calculate the no of Saturdays or Sundays between a start date and end date.
CREATE FUNCTION dbo.WEEKEND_COUNT
(
#Start_Date datetime,
#End_Date datetime
)
RETURNS int
AS
BEGIN
Declare #count int = 0;
while #Start_Date<=#End_Date
Begin
IF DatePart(WEEKDAY,#Start_Date) = 1 or DatePart(WEEKDAY,#Start_Date) = 7
SET #count=#count+1
SET #Start_Date=DateAdd(d,1,#Start_Date)
END
return #count
END
--Use below to get the count of Saturdays and Sundays
Select dbo.WEEKEND_COUNT('Your start date','your end date')
This will give you the number of sunday between two dates
SELECT DateDiff(ww, #dFrom, #dTo) as NumOfSundays

Resources