0

What is the preferred method of adding the current date/time into an SQL Server table with INSERT Command and executenonquery? I'm expecting something like ...

        cmd.Parameters.Add("@theDate", SqlDbType.VarChar, 20)
        cmd.Parameters("@theDate").Value = "getdate()"

5 Answers 5

2

First of all, you should use DateTime data type for column. Second, on that column you can use DefaultValue=getdate() constraint, so it is defined only in DB. Application do not need to insert it.

Sign up to request clarification or add additional context in comments.

3 Comments

That would be convenient. I'll check into it.
Downvoters should explain what is wrong as defined in SO policy. This is perfectly reliable and standard way of doing things, i want to know what is incorrect.
Thomas, I'm not sure what you mean. I didn't downvote your answer. In fact, I upvoted it, because it's informative. MF's answer worked for me immediately. I can't check your answer right now (though I assume it will work), because the only access I have to the database is through the aspx programs I write myself - and the database admin is on vacation. I appreciate your response. thanks, tff.
1

How about...

cmd.Parameters.Add("@theDate", SqlDbType.DateTime)
cmd.Parameters("@theDate").Value = DateTime.Now

3 Comments

That worked! I can't mark this as the correct answer for a few more minutes, but thanks!
-1 Setting date of insertion should be handled by DB, not application.
@Tomas His question was very specific, and this answers that question. If the date is ever anything besides the current time, then a default value in the database isn't sufficient and he'll need to know how to do this.
1
cmd.Parameters("@theDate").Value = Now()

Comments

1

The date/time parameter is NOT needed.

Anytime the stored procedure is called, you just update the date/time field at the server level.

If you want to be able to update the date/time field to something OTHER than the current time then you can add an optional parameter on the stored procedure; this way you server can update it to getdate() when it is null, or you can pass it from the application when it needs to be a specific time.

The reason Tomas emphasized the importance of setting the time at the server level is because of time zones and other factors.

Comments

0

I would look to see if you can place the text current_timestamp directly into the sql code, and skip the parameter entirely. If you can't, then it's time to just use DateTime.Now.

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.