How can I call a sqlserver function from VB.net(or C#) ? Is there some syntax like stored procedure?

前端 未结 5 1102
囚心锁ツ
囚心锁ツ 2020-12-16 05:48
Public Sub cleanTables(ByVal prOKDel As Short)
     Dim sqlParams(1) As SqlParameter
     Dim sqlProcName As String
     sqlProcName = \"db.dbo.sp_mySP\"
     sqlPar         


        
5条回答
  •  青春惊慌失措
    2020-12-16 06:35

    This works for me and is based on one of the above answers 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;
    

提交回复
热议问题