从存储过程返回变量

时间:2015-05-19 12:06:59

标签: c# asp.net sql-server-2008 stored-procedures

我需要让员工开始约会。我想要做的是当选中一个复选框时,调用数据库获取日期并将其返回到我的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

2 个答案:

答案 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
}