我有两个类Program.cs
和DataAccessLayer.cs
。
我有一个在DataAccessLayer
中"活着"的存储过程。
我要做的是当Program.cs
运行时,我需要它将两个参数(@Department1
和@Department2
)传递给DAL中的存储过程。
在Program
中调用DAL方法后,我需要将存储过程存储在文件中。我知道我将不得不两次调用DAL方法(一次是Dept1,第二次用于Dept2)。
我的问题是:如何格式化程序方法以传递dept1的参数,然后将这些结果存储在Excel文件中?
我假设一旦我在Dept1的程序类中获得该方法,我就可以将其复制并粘贴到Dept2中,然后更改需要通过的参数(@Depption2)。
我不必担心 @startdate/@ @enddate参数,因为这些参数不会随着存储过程的每个运行而变化。
应该注意的是,我的变量(@departmentid)是存储过程中的静态变量。
基本上,该存储过程旨在做的是采用Dept1的参数,该应用程序将将其放入文件中的返回结果。
然后,我再次使用DEPT2参数调用有关方法,然后返回这些结果。希望这有意义...
这就是我目前在DAL中的...
public bool GetDeptData(SqlConnection Conn, string StartDate,string EndDate, out DataTable DTDepartmentData)
{
SqlDataAdapter adapter = null;
SqlCommand cmd = null;
DateTime startDate = new DateTime();
DateTime endDate = new DateTime();
SqlDbType DepartmentID = new SqlDbType();
DTDepartmentData = new DataTable();
try
{
// Set our start date and end date for last month
startDate = DateTime.Parse(
DateTime.Now.AddMonths(-1).Year.ToString() + "-" +
DateTime.Now.AddMonths(-1).Month.ToString() + "-01 00:00:00");
endDate = DateTime.Parse(
DateTime.Now.AddMonths(-1).Year.ToString() + "-" +
DateTime.Now.AddMonths(-1).Month.ToString() + "-" +
DateTime.DaysInMonth(DateTime.Now.AddMonths(-1).Year, DateTime.Now.AddMonths(-1).Month) + " 23:59:59");
// Call our stored procedure and populate the datatable with the Dept data
adapter = new SqlDataAdapter();
cmd = new SqlCommand("sp_EXAMPLESP", Conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = endDate;
cmd.Parameters.Add("@DepartmentID", SqlDbType.VarChar).Value = "departmentID";
adapter.SelectCommand = cmd;
adapter.Fill(DTDepartmentData);
return true;
}
catch (Exception CaughtError)
{
this.ErrorMsg = "An error occurred in the GetDeptData method: " + CaughtError.ToString() + " || " + Environment.NewLine;
return false;
}
将decr验该值从main到您的dal方法开始更改getDeptData方法的签名
public bool GetDeptData(string StartDate,string EndDate, string deptId, out DataTable DTDepartmentData)
{
// The SqlConnection should be created here and destroyed
// here, everytime you call this method
using(SqlConnection con = new SqlConnection(....connectionstring....))
{
// then use the deptId value in the creation
// of the parameter @DepartmentId
.....
cmd.Parameters.Add("@DepartmentID", SqlDbType.VarChar).Value = deptId;
adapter.Fill(DTDepartmentData);
return true;
}
}
catch(Exception ....)
{
...
}
现在在您的program.cs中您应该创建一个DAL类的实例,并调用通过所需值
的方法 DataTable dtResult = null;
string startDate = SomeCodeToGetTheStartDate();
string endDate = SomeCodeToGetTheEndDate();
string deptId = SomeCodeToGetTheDeptId();
MyDALClass cs = new MyDALClass();
if(cs.GetDeptData(startDate, endDate, deptId, out dtResult)
.... success ....
旁注:您确定dectmentID是字符串值而不是整数吗?