从存储过程返回datetime

时间:2015-08-22 01:20:23

标签: c# asp.net sql-server

我有这个问题:

CREATE PROCEDURE [dbo].[spGetWhenTaskLastRun]   
    @dt datetime out         
AS
BEGIN
    SELECT  
        @dt = whenTaskLastRan
    FROM
        [dbo].[t_whenTaskLastRan]   
END

以及执行此查询的C#代码:

SqlDataReader reader;

string ConnectionString = SafaConnectionString.ConnectionString;

SqlConnection Connection = new SqlConnection(ConnectionString);

SqlCommand cmd = new SqlCommand("spGetWhenTaskLastRun", Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@dt", SqlDbType.DateTime);
cmd.Parameters["@dt"].Direction = ParameterDirection.Output;

try
{
    Connection.Open();
    reader = cmd.ExecuteReader();

    if (reader.HasRows)
        return (DateTime)cmd.Parameters["@dt"].Value;
    else
        return DateTime.Now;
}

但它始终返回reader.HasRows = false并且没有记录。

我的查询错了吗?

1 个答案:

答案 0 :(得分:5)

存储过程未返回结果集;它只分配输出参数值。请改用ExecuteNonQuery方法。如果没有行符合条件或列值为NULL,则输出参数将为NULL

cmd.ExecuteNonQuery();
if (cmd.Parameters["@dt"].Value == DBNull.Value)      
    return (DateTime)cmd.Parameters["@dt"].Value;
else
    return DateTime.Now;