使用存储过程计算星期一作为一周的第一天

时间:2013-12-10 19:32:53

标签: c# asp.net sql sql-server

我有这个C#代码来提取上周创建的帖子数量,这很好。但它从“过去7天”拉起数量;我想要做的是将一周的第一天设置为“星期一”,这样当我们拉出“周”的发布计数时,它应该从“星期一到星期日”而不是默认“最后一天”拉出数字。 7天“。

我创建了一个类,将星期一设置为一周的第一天,但​​我想知道的是我怎么能(如果可以的话)将该方法封装在此代码中以简单地提取发布次数等

这是我的代码:

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);
}

存储过程:

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

2 个答案:

答案 0 :(得分:1)

在您的存储过程中尝试此操作:

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

答案 1 :(得分:0)

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())

要从上周一开始选择7天,请在C#中迭代最后7天,直到您点击星期一,然后将该日期传递到SQL Proc。

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