-1

我有以下代码:

Connection c = new Connection();

string select1 =      
   @"SELECT 
       E.employeeNumber AS 'Employee Number', 
       E.employeePrivateName + ' ' + E.employeeFamilyName AS 'Employee Name', 
       DATEDIFF (MONTH, E.startWorkingDate, GETDATE()) AS 'Seniority in Month', 
       M.machineName AS 'Machine Name', J.jobName AS 'Job Name', 
       COUNT(E.employeeNumber) AS 'Number of Times on Machine in Specif Job', 
       SUM(Number_Of_Days_During_The_Period) AS 'Total Working Days on Machine in Specif Job', 
       SUM(Salary_per_Period) AS 'The Salary For working on Machine in Specif Job' 
    FROM 
       TblEmployee E 
    INNER JOIN 
       AllSchedules A_S on E.employeeNumber = A_S.employeeNumber 
    INNER JOIN 
       TblJob J on J.jobNumber = A_S.jobNumber 
    INNER JOIN 
       TblMachine M on M.machineNumber = A_S.machineNumber 
    INNER JOIN 
       TblPeriod P on P.Number = A_S.periodNumber 
    WHERE 
       Month(P.fromDate) = Month(@Month) 
    GROUP BY 
       E.employeeNumber, E.employeePrivateName, E.employeeFamilyName, 
       E.startWorkingDate, M.machineName, J.jobName 
    ORDER BY 
       E.employeeFamilyName , E.employeePrivateName";

SqlCommand cmd = new SqlCommand(select1, c.con);
DateTime month = comboBox1.Text;

cmd.Connection = c.con;
cmd.Parameters.AddWithValue("@Month", month);

SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd); //c.con is the      connection string

SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

DataSet ds = new DataSet();
dataAdapter.Fill(ds);

dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];

我想运行查询,但是我需要定义一个日期时间值,以便它成为查询的搜索参数。如何保存 DateTime 变量以使其保存月份数(10 月等)

谢谢

4

4 回答 4

2

在您的查询中,您有此行用于 WHERE 条件

WHERE Month(P.fromDate)= Month(@Month) 

T-SQL 的MONTH函数期望接收一个 Date 作为它的参数,所以你可能只需要

DateTime dt = new DateTime(DateTime.Today.Year, month, 1);

并将此值传递给参数@Month

cmd.Parameters.AddWithValue("@Month", dt);

编辑:如果您有一个组合框,其中的项目填充了订购的月份名称:(一月,二月......)

// In array the indexes start at zero.....
if(cboMonths.SelectedIndex >= 0)
{
    int month = cboMonts.SelectedIndex + 1;

}
于 2013-08-11T15:21:39.100 回答
0
string sMonth = DateTime.Now.ToString("MM");
于 2013-08-11T15:20:43.877 回答
0

鉴于 SQLMonth函数返回一个整数(Source),您需要替换:

"... WHERE Month(P.fromDate)= Month(@Month) GROUP BY ..."

经过

"... WHERE Month(P.fromDate) = " + intMonth.ToString() + " GROUP BY ..."

其中intMonth是从组合框中选择的月份的整数值。

但是,您需要确保它只是一个整数并且不能用作注入攻击。您最好将所有 SQL 放入存储过程中并将月份作为整数参数传递。

于 2013-08-11T15:27:39.980 回答
0

您可以使用

string monthString = DateTime.ParseExact(comboBox1.Text, "MMMM", CultureInfo.CurrentCulture ).Month.ToString("MM");

并将其转换为整数:

int month = int.Parse(monthString);
于 2013-08-11T15:31:14.000 回答