开发者

ExecuteScalar always returns null when calling a scalar-valued function

Why does this return null?

//seedDate is set to DateTime.Now; con is initialized and open. Not a problem with that
using (SqlCommand command = new SqlCommand("fn_last_business_date", con))
{
       command.CommandType = CommandType.StoredProcedure;
       command.Parameters.AddWithValue("@seed_date", seedDate);//@seed_date is the param name
       object res = command.ExecuteScalar(); //res is always null 
}

But when I call this directly in the DB as follows:

select dbo.fn_last_busine开发者_开发技巧ss_date('8/3/2011 3:01:21 PM') 
returns '2011-08-03 15:01:21.000' 

which is the result I expect to see when I call it from code

Why, why, why?


Why does everyone insist on the select syntax?..

using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("calendar.CropTime", c))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.DateTime).Direction = ParameterDirection.ReturnValue;
    cmd.Parameters.AddWithValue("@d", DateTime.Now);

    cmd.ExecuteNonQuery();

    textBox1.Text = cmd.Parameters["@RETURN_VALUE"].Value.ToString();

}


try:

using (SqlCommand command = new SqlCommand("select dbo.fn_last_business_date(@seed_date)", con))
{
       command.CommandType = CommandType.Text;
       command.Parameters.AddWithValue("@seed_date", seedDate);//@seed_date is the param name
       object res = command.ExecuteScalar(); //res is always null 
}


You are actually getting an error that isn't being caught. You don't call scalar udfs like you call stored procedures.

Either wrap the udf in a stored proc, or change syntax. I'm not actually sure what that is because it isn't common...

Ah ha: see these questions:

  • How to use SQL user defined functions in .NET?
  • Calling user defined functions in Entity Framework 4
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜