Reputation: 121
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
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
Reputation: 18051
I see some issues in your code:
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