Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_business_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?

like image 617
Icarus Avatar asked Aug 03 '11 19:08

Icarus


People also ask

Can ExecuteScalar return null?

the OracleCommand ExecuteScalar returns an object for the result. It's not strongly typed because the SQL statement is arbitrary, so the type isn't known until it's parsed (which is by the DB engine, not by the . NET runtime). The object returned can be null .

What does ExecuteScalar return?

ExecuteScalar Method. Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored.

What is SQL scalar value?

An SQL scalar function is a user-defined function written in SQL and it returns a single value each time it is invoked. SQL scalar functions contain the source code for the user-defined function in the user-defined function definition.

What is execute scalar function SQL?

The following example creates a SqlCommand and then executes it using ExecuteScalar. The example is passed a string representing a new value to be inserted into a table, and a string to use to connect to the data source. The function returns the new Identity column value if a new row was inserted, 0 on failure.


1 Answers

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

}
like image 101
GSerg Avatar answered Nov 07 '22 15:11

GSerg