开发者

SQLServer INSERT getdate() function using parameters

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()"


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.


How about...

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


cmd.Parameters("@theDate").Value = Now()


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜