存储过程输出错误

时间:2015-10-23 08:52:54

标签: sql sql-server asp.net-mvc stored-procedures

我有这个存储过程,它返回选定周的数据,如公司名称预期工作 2015年10月19日至2015年10月25日之间的工作(每个例子)。

我刚刚添加了预期的工作线,并且出于某种奇怪的原因,当值相同时,输出会从一周到另一周不同。

Company1 - Christopher - 35 - 35 |在一周内可以在另一周上给出以下内容:

Company1 - Christopher - 350 - 35

我已经意识到当完成工作有值时,值不正确,如果没有记录工作预期工作有权利值。

以下是程序:

ALTER procedure [dbo].[spGetWeeklyActivityByEmployee]
      @startDate date
    , @endDate date
as
    set datefirst 1 -- Monday

    select 
        Company.Name as [Company]
        , Employee.FirstName + ' ' + Employee.LastName as [Name]        
        , sum(UserActivity.Cost) as [Recorder Time]
        , sum(Employee.ExpectedTime) as [Expected Time] // I have added this line, not sure if it's correct
    from 
        dbo.Employee
    inner join 
        dbo.Company on Company.CompanyId = Employee.CompanyId
    left join 
        dbo.UserActivity on UserActivity.Login = Employee.Login
                         and UserActivity.CalendarDate >= @startDate
                         and UserActivity.CalendarDate <= @endDate
    where 
        (Employee.EntranceDate is null
         or YEAR(Employee.EntranceDate) < YEAR(@startDate)
         or (YEAR(Employee.EntranceDate) = YEAR(@startDate) 
         and DATEPART(WEEK, Employee.EntranceDate) <= DATEPART(WEEK, @startDate)))
        and (Employee.ExitDate is null
             or YEAR(Employee.ExitDate) > YEAR(@endDate)
             or (YEAR(Employee.ExitDate) = YEAR(@endDate) 
             and DATEPART(WEEK, Employee.ExitDate) >= DATEPART(WEEK, @endDate)))
    group by 
        Company.Name, Employee.FirstName + ' ' + Employee.LastName

    return 0

我错过了什么吗?我检索预期时间错误的方式是什么?

编辑:

以下是代码中我将信息保存在数组中的部分:

// create and open a connection object
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();

// 1.  create a command object identifying
//     the stored procedure
SqlCommand cmd = new SqlCommand("spGetWeeklyActivityByEmployee", conn);

// 2. set the command object so it knows
//    to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;

// 3. add parameter to command, which
//    will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@startDate", wk1));
cmd.Parameters.Add(new SqlParameter("@endDate", wk2));

// execute the command
rdr = cmd.ExecuteReader();         

string[] tab_company = new string[31]; // Don't mind the sizes
string[] tab_name = new string[31];
string[] tab_expectedtime = new string[31];
string[] tab_rectime = new string[31];

int counter;

counter = 0;

while (rdr.Read())
{
    tab_company[counter] = rdr["Company"].ToString();
    tab_name[counter] = rdr["Name"].ToString();
    tab_expectedtime[counter] = rdr["Expected Time"].ToString();
    tab_rectime[counter] = rdr["Recorder Time"].ToString();

    counter++;               
}

也许价值的变化来自这里?

1 个答案:

答案 0 :(得分:0)

SUM()中删除Employee.ExpectedTime并将其添加到GROUP BY