Rashmi
Rashmi

Reputation: 121

C# sqlserver stored procedure parameters

I have a stored procedure that has an update statement. It takes 3 parameters: ID,Status,Date

I have written a C# program to call this procedure. If the status is -1, I want the date to be null in the table and if status is 1, date should be current date.

Int32 rowsAffected = 0;
string datenow =null;

using (SqlConnection connection = new    SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
    connection.Open();
    SqlCommand cmd = new SqlCommand(
        "usp_UpdateProc", connection);

    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@status", SqlDbType.Int);
    cmd.Parameters["@status"].Value = status;
    if(status != 1)
        datenow = DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt");

    cmd.Parameters.AddWithValue("@datenow", @datenow);
    cmd.Parameters.Add(
        new SqlParameter("@ID", @ID));

    try
    {
        rowsAffected = cmd.ExecuteNonQuery();
    }
    catch (Exception ep)
    {  //throw ep
    }

When I do this status and date fields are both nulls in Database. I am not sure why this is happening? Thanks Rashmi

Upvotes: 1

Views: 355

Answers (2)

pquest
pquest

Reputation: 3290

I would try to assign the values like this instead and see if it makes a difference:

SqlParameter stat = cmd.Parameters.AddWithValue("@status" ,status);
stat.dbType = SqlDbType.Int;

DateTime? dt = (status == -1)? null : DateTime.Now;

SqlParameter dateParam = cmd.Parameters.AddWithValues("@datenow", dt ?? DBNull.Value);
dateParam.dbType = SqlDbType.DateTime;

Upvotes: 1

Larry
Larry

Reputation: 18051

I see some issues in your code:

  • The test is wrong and need to be fixed so a NULL is used as @datenow value if status is -1
  • I am not sure about the DateNow which is passed as a string. What dont you use the native .NET DateTime value ?
  • The results highly depends on the way the stored procedure is implemented.

Please do not put empty try/catches and display the exception instead so you can better see what is going wrong.

I suggest this:

SqlCommand cmd = new SqlCommand("usp_UpdateProc", connection);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@status", status);
if(status == -1)
    cmd.Parameters.AddWithValue("@datenow", DBNull.Value);
else
    cmd.Parameters.AddWithValue("@datenow", DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt"));

cmd.Parameters.AddWithValue("@ID", @ID);

try
{
    rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ep)
{ 
    MessageBox.Show(ep.ToString());
}

Upvotes: 1

Related Questions