0

I have an SQL command in my code behind as:

cmd = new SqlCommand("insert into MappingInfo(ActivationDate) values (@ActivationDate)", con);

I want to assign 'current timestamp' or 'null' to @ActivationDatebased on some condition, as shown below:

int ActivateState;
if (rdoActivateMappingYes.Checked)
{
    ActivateState = 1;
    cmd.Parameters.AddWithValue("@ActivationDate", "CURRENT_TIMESTAMP");
}
else
{
    ActivateState = 0;
    cmd.Parameters.AddWithValue("@ActivationDate", DBNull.Value);
}

However, upon running the web app, I am getting the following error:

{System.Data.SqlClient.SqlException} : {"Conversion failed when converting date and/or time from character string."}
3
  • "CURRENT_TIMESTAMP" is a string, not a DateTime or something. How about using your local time as DateTime.Now or your UTC time (as a better way of course) as DateTime.UtcNow? Commented Dec 9, 2014 at 15:02
  • @SonerGönül I understood that! Can you please tell me how to enter the current timestamp? What is the correct approach? Commented Dec 9, 2014 at 15:04
  • You would be better served if you defined your datatypes for your parameters instead of forcing the system to figure it out. blogs.msmvps.com/jcoehoorn/blog/2014/05/12/… Commented Dec 9, 2014 at 15:11

3 Answers 3

4
int ActivateState;
if (rdoActivateMappingYes.Checked)
{
    ActivateState = 1;
    cmd.Parameters.AddWithValue("@ActivationDate", DateTime.Now);
}
else
{
    ActivateState = 0;
    cmd.Parameters.AddWithValue("@ActivationDate", DBNull.Value);
}
Sign up to request clarification or add additional context in comments.

Comments

3

The message is clear.

The field ActivationDate is a DateTime field, but you are passing a string as value: "CURRENT_TIMESTAMP"

Probably you will have to pass a DateTime value, as DateTime.Now, or any other DateTime that suits the logic of your app/database.

2 Comments

I understood that! Can you please tell me how to enter the current timestamp? What is the correct approach?
@AniruddhaPondhe, use DateTime.Now, or DateTime.UtcNow (mentioned by rodrigoqg)
0

You can use Datetime.parse() method to check if the string is in valid date format.

DateTime date = DateTime.Parse("01/01/1900");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.