Calling SQL Functions directly from C#

后端 未结 6 764
遇见更好的自我
遇见更好的自我 2021-02-08 12:49

I have a requirement to run a query against a database that will return either a zero or one (Checking for existance of specific criteria). The Tech specs I\'ve been given for r

6条回答
  •  梦毁少年i
    2021-02-08 13:03

    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;
    

提交回复
热议问题