Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
The problem is I am stuck at how to output 28/30/31 days according to user's choice of certain month and year, here is my code:

What I have tried:

declare @FromDate as datetime;
declare @ToDate as datetime;
declare @OperID as varchar(20) = 'OP1';
declare @Year as int = 2018
declare @Month as int = 1

set @FromDate = convert(date,convert(varchar,@Year) + '-' + convert(varchar,@Month) + '-01')
set @ToDate = dateadd(d,-1,DATEADD(m, 1, @FromDate))

select Branch_no, operid, clock_date, [I], [O]
from
( select Branch_no, operid, 
    convert(date, clock_date) as clock_date, 
    convert(time, clock_date) as clock_time, 
    clock_type, Workstation_no
  from ROSTER_TIMECLOCK
  where Clock_date >=CONVERT(DATETIME, @FromDate, 102)
    and Clock_date <=CONVERT(DATETIME, @ToDate, 102)
    and OperID=@OperID
) as TheClock
PIVOT
( min(clock_time)
  FOR clock_type in ([I],[O])
) as ThePivot 
Posted
Updated 10-Feb-18 16:23pm
Comments
RedDk 29-Jan-18 13:56pm    
Qu'est-ce que c'est "ROSTER_TIMECLOCK"?
Member 11850495 29-Jan-18 17:22pm    
ROSTER_TIMECLOCK is the table that I do the query.
Richard Deeming 30-Jan-18 12:36pm    
@FromDate and @ToDate are already datetime values, so there's no need to CONVERT them.

Other than that, I can't see anywhere in your code that would generate a fixed number of days. You're selecting all of the records which fall within the month, so what's the problem?
Herman<T>.Instance 1-Feb-18 8:07am    
--> WHERE MONTH(Clock_Date) = @Month AND YEAR(Clock_Date) = @Year AND OperID=@OperID


Then you select all month data for a given year, so 28/29/30 or 31 days is no issue!
Member 11850495 1-Feb-18 19:27pm    
Thank you sir

1 solution

declare @Year as int = 2018
declare @Month as int = 1
select day(dateadd(dd,-1,dateadd(mm,1,datefromparts(@Year,@Month,1))))
 
Share this answer
 
Comments
Richard Deeming 13-Feb-18 12:28pm    
DateFromParts[^] was added in SQL Server 2012. At the same time, they added EOMonth[^] to get the last day of the month, which would simplify your code slightly. :)

SELECT Day(EOMonth(DateFromParts(@Year, @Month, 1)))

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900