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

为什么这会返回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 } 

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

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

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

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

尝试:

 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 } 

为什么每个人都坚持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(); } 

您实际上收到的错误是未被捕获的。 你不像调用存储过程那样调用标量udfs。

将udf包装在存储过程中,或更改语法。 我真的不确定那是什么因为它不常见……

啊哈:看到这些问题:

  • 如何在.NET中使用SQL用户定义的函数?
  • 在Entity Framework 4中调用用户定义的函数