Calling SQL Functions directly from C# Calling SQL Functions directly from C# sql sql

Calling SQL Functions directly from C#


Execute the Stored Procedure using the ExecuteScalar() method. You can then cast the result of this to a boolean.

e.g

   SqlConnection con = new SqlConnection(connectionString);    SqlCommand com = new SqlCommand("Execute dbo.usp_MyStoredProc", con);    return (Boolean)com.ExecuteScalar();


This works for me and is based on this answer https://stackoverflow.com/a/3232556/1591831 using a SqlDataAdapter (note that you do not need to use one) and ExecuteScalar (can use ExecuteNonQuery as shown here):

bool res = false;using (SqlConnection conn = new SqlConnection(GetConnectionString())){    using (SqlCommand comm = new SqlCommand("dbo.MyFunction", conn))    {        comm.CommandType = CommandType.StoredProcedure;        SqlParameter p1 = new SqlParameter("@MyParam", SqlDbType.Int);        // You can call the return value parameter anything, .e.g. "@Result".        SqlParameter p2 = new SqlParameter("@Result", SqlDbType.Bit);        p1.Direction = ParameterDirection.Input;        p2.Direction = ParameterDirection.ReturnValue;        p1.Value = myParamVal;        comm.Parameters.Add(p1);        comm.Parameters.Add(p2);        conn.Open();        comm.ExecuteNonQuery();        if (p2.Value != DBNull.Value)            res = (bool)p2.Value;    }}return res;


The calling scalar-valued function is absolutely correct solution.