调用标量值函数时,ExecuteScalar始终返回null

Ica*_*rus 4 c# sql sql-server sql-function

为什么这会返回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 
}
Run Code Online (Sandbox Code Playgroud)

但是当我直接在DB中调用它时如下:

select dbo.fn_last_business_date('8/3/2011 3:01:21 PM') 
returns '2011-08-03 15:01:21.000' 
Run Code Online (Sandbox Code Playgroud)

当我从代码中调用它时,我希望看到的结果

为什么,为什么,为什么?

GSe*_*erg 23

为什么每个人都坚持select语法?

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();

}
Run Code Online (Sandbox Code Playgroud)

  • 我不知道那些没有发表评论的挫折者是否真的证明了上述错误,或者只是认为嘿,这不是我通常做的事情. (6认同)
  • 就像评论一样,如果我记得很清楚,只是为了说清楚,当你使用一个函数时,返回值必须是参数集合的第一个参数,如果函数需要更多的参数. (2认同)
  • +1 - 这项技术有效。但请注意以下警告 - 仅当 UDF 是标量值 UDF 时,以这种方式将 UDF 视为存储过程才有效。如果 UDF 是值为 1 的表(内联或多语句),那么您将收到类似以下错误:“对过程 'Name_Of_UDF' 的请求失败,因为 'Name_Of_UDF' 是表值函数对象。” (2认同)
  • @Moe哦,是的.调用*标量*UDF是OP问题的重点. (2认同)

jen*_*ent 7

尝试:

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 
}
Run Code Online (Sandbox Code Playgroud)