简体   繁体   中英

Calculate Monday as first day of the week with a stored procedure

I have this C# code to pull up the number of postings created within the last week, which is working fine. But it's pulling up count from "last 7 days"; what I want to do is to set the first day of the week to "Monday" so that when we pull up the count of posting for "week", it should pull up the number from "monday to sunday" instead of default "last 7 days".

I created a class to set Monday as the 1st day of the week, but what I want to know is how can I (if I can) encapsulate that method in this code to simply pull count of posting etc

Here is my code:

if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
{
    lblJobPostings.Text = ds.Tables[0].Rows[0]["new_job_posting_this_week"].ToString();
}
if (ds.Tables[1] != null && ds.Tables[1].Rows.Count > 0)
{
    lblNewEmployers.Text = ds.Tables[1].Rows[0]["new_employer_this_week"].ToString();
}
if (ds.Tables[2] != null && ds.Tables[2].Rows.Count > 0)
{
    lblNewInstitutes.Text = ds.Tables[2].Rows[0]["new_institutes_this_week"].ToString();
}

public static DateTime CallFirstDayOfWeek(DateTime input)
{
   int Delta = (7 - (DayOfWeek.Monday - input.DayOfWeek)) % 7;
   return input.AddDays(-Delta);
}

Stored procedure:

select COUNT(od.id) [new_job_posting_this_week] 
from rs_job_posting od
where od.date_created = GETDATE()-7

Try this in your Stored Procedure:

DECLARE @CurrentWeekday AS INT
DECLARE @LastSunday AS DATETIME
DECLARE @LastMonday AS DATETIME

SET @CurrentWeekday = DATEPART(WEEKDAY, GETDATE())
// Count backwards from today to get to the most recent Sunday.
// (@CurrentWeekday % 7) - 1 will give the number of days since Sunday; 
// -1 negates for subtraction.
SET @LastSunday = DATEADD(DAY, -1 * (( @CurrentWeekday % 7) - 1), GETDATE())
// Monday is obviously one day after last Sunday.
SET @LastMonday = DATEADD(DAY, 1, @LastSunday)

SELECT COUNT(od.id) [new_job_posting_this_week] 
FROM rs_job_posting od
WHERE od.date_created >= @LastMonday
select COUNT(od.id) [new_job_posting_this_week] 
from rs_job_posting od
where od.date_created Between Convert(DateTime, DATEADD(D,-7,GETDATE())) And Convert(DateTime, GetDate())

To select 7 days starting on say last Monday, iterate through the last 7 days in C# until you hit Monday, then pass that date into the SQL Proc.

for (int i = 0; i < 7; i++)
            {
                DateTime mydate = DateTime.Now.AddDays(-1);
                if (mydate.DayOfWeek == DayOfWeek.Monday)
                {
                    //call sp here
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM