Few people are as die hard about using Stored Procedures as I am. I love everything about them, period. However, one common mistake that people make when moving to ADO.NET is forgetting to supply a value for a given parameter. Hence, when the command is executed, an exception is thrown indicating that a parameter value is missing. Remember that when you are using T-SQL in Query Analyzer for instance, you can call your procs passing parameters by position or name. You can effectively do the same in ADO.NET by not specifying a parameter name, but that's sloppy and error prone.
Anyway, depedning on your proc, it may be useful to supply default values for your procs. Beware though that if you do this, you may inadvertantly introduce subtle bugs in your code because you won't get the warning message.
Here's all there is to it:
| CREATE PROCEDURE usp_CalculateValue @p_FirstValue INT = 0 ,@p_SecondValue INT = 0 ,@p_TaxRate DEC(4) = 50 AS SELECT (@p_FirstValue + @p_SecondValue) * @p_TaxRate GO |
| SqlConnection cn = new SqlConnection("ConnectString"0; SqlCommand cmd = new SqlCommand("usp_CalcluateValue", cn); cmd.CommandType = CommandType.StoredProcedure; if(cn.State <> ConnectionState.Open){cn.Open();} int i = cmd.ExecuteScalar(); //returns 0 SqlConnection cn = new SqlConnection("ConnectString"0; SqlCommand cmd = new SqlCommand("usp_CalcluateValue", cn); cmd.CommandType = CommandType.StoredProcedure; if(cn.State <> ConnectionState.Open){cn.Open();} cmd.Parameters.Add("@p_FirstValue", 5); int i = cmd.ExecuteScalar(); //returns 250 SqlConnection cn = new SqlConnection("ConnectString"0; SqlCommand cmd = new SqlCommand("usp_CalcluateValue", cn); cmd.CommandType = CommandType.StoredProcedure; if(cn.State <> ConnectionState.Open){cn.Open();} cmd.Parameters.Add("@p_SecondValue", 5) int i = cmd.ExecuteScalar(); //returns 250 SqlConnection cn = new SqlConnection("ConnectString"0; SqlCommand cmd = new SqlCommand("usp_CalcluateValue", cn); cmd.CommandType = CommandType.StoredProcedure; if(cn.State <> ConnectionState.Open){cn.Open();} cmd.Parameters.Add(5); int i = cmd.ExecuteScalar(); //returns 250 SqlConnection cn = new SqlConnection("ConnectString"0; SqlCommand cmd = new SqlCommand("usp_CalcluateValue", cn); cmd.CommandType = CommandType.StoredProcedure; if(cn.State <> ConnectionState.Open){cn.Open();} cmd.Parameters.Add(5); cmd.Parameters.Add(5) int i = cmd.ExecuteScalar(); //returns 500 SqlConnection cn = new SqlConnection("ConnectString"0; SqlCommand cmd = new SqlCommand("usp_CalcluateValue", cn); cmd.CommandType = CommandType.StoredProcedure; if(cn.State <> ConnectionState.Open){cn.Open();} cmd.Parameters.Add("@p_FirstValue", 5); cmd.Parameters.Add("@p_SecondValue", 5) int i = cmd.ExecuteScalar(); //returns 500 |