Calling Oracle stored procedure from C#?

后端 未结 7 2155
说谎
说谎 2020-11-27 06:10

How does one call a stored procedure in oracle from C#?

7条回答
  •  粉色の甜心
    2020-11-27 06:18

    Instead of

    cmd = new OracleCommand("ProcName", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
    

    You can also use this syntax:

    cmd = new OracleCommand("BEGIN ProcName(:p0); END;", con);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
    

    Note, if you set cmd.BindByName = False (which is the default) then you have to add the parameters in the same order as they are written in your command string, the actual names are not relevant. For cmd.BindByName = True the parameter names have to match, the order does not matter.

    In case of a function call the command string would be like this:

    cmd = new OracleCommand("BEGIN :ret := ProcName(:ParName); END;", con);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.Add("ret", OracleDbType.RefCursor, ParameterDirection.ReturnValue);    
    cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
    // cmd.ExecuteNonQuery(); is not needed, otherwise the function is executed twice!
    var da = new OracleDataAdapter(cmd);
    da.Fill(dt);
    

提交回复
热议问题