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?
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 .
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With