我需要让员工开始约会。我想要做的是当选中一个复选框时,调用数据库获取日期并将其返回到我的C#代码中。我想我的所有设置都接近完美,但我的调用过程返回错误。有人可以帮助我设置语法,以便在选中复选框时,它将调用数据库,运行存储过程,并将结果(作为日期时间)从存储过程返回到我的C#语法中吗? / p>
编辑---抛出的错误是: 不能隐式地将类型'System.DateTime'转换为'string'
//Calling Procedure
this.txtStartDate.Text = getHireDate(Constants.Database, employeename);
//Actual Procedure
private static string getHireDate(string Database, string employeename)
{
SqlConnection connection = new SqlConnection(Database);
SqlCommand command = new SqlCommand("_uspGetHireDate", connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameter returnValue = new SqlParameter("returnVal", SqlDbType.Int);
returnValue.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnValue);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
//This line throws an error of can not implicitly convert 'System.DateTime' to 'string'
return Convert.ToDateTime(returnValue.Value);
}
//Stored Procedure Being Called
alter procedure [dbo].[_uspGetHireDate]
(
@employeename varchar(100)
)
as
declare @StartDate datetime
set NOCOUNT ON
Set @StartDate = (SELECT CONVERT(VARCHAR(10), HireDate, 101)
FROM tbl_employeeinformation
where hiredate is not null
AND active = 1
AND employeename = @employeename
return @StartDate
答案 0 :(得分:3)
你的解决方案非常混乱。为什么要将DATE
转换为VARCHAR
,然后将其作为INT
返回,然后将其转换为DateTime
并返回为STRING
???
首先将您的stored procedure
更改为返回值标准方式。使用DATE
返回INT
,而不是return
:
alter procedure [dbo].[_uspGetHireDate]
@employeename varchar(100)
as
set NOCOUNT ON
SELECT HireDate
FROM tbl_employeeinformation
where hiredate is not null
AND active = 1
AND employeename = @employeename
然后更改您的方法以返回DateTime
:
private static DateTime getHireDate(string Database, string employeename)
{
SqlConnection connection = new SqlConnection(Database);
SqlCommand command = new SqlCommand("_uspGetHireDate", connection);
command.CommandType = CommandType.StoredProcedure;
connection.Open();
var result = Convert.ToDateTime(command.ExecuteScalar());
connection.Close();
return result;
}
感谢@petelids指出这一点。将您的presentation layer
更改为:
this.txtStartDate.Text = getHireDate(Constants.Database, employeename).ToString("yyyy-MM-dd");
或任何适当的格式。可视化数据是presentation layer
而不是business layer
的作品。在这里,您将connection string
存储在presentation layer
中,这有点奇怪。
还要将您的连接,命令等放在using
块中并使用try-catch
块。
另外,我注意到您没有将@employeename
参数传递给stored procedure
。
答案 1 :(得分:1)
您将按照函数返回类型
中的预期返回DateTime
而不是string
private static string getHireDate(string Database, string employeename)
{
----
return Convert.ToDateTime(returnValue.Value); // Here you are returning datetime but your return type should be string as your function return type is string
}