Set a DateTime database field to "Now"

Sql Servervb.net

Sql Server Problem Overview


In VB.net code, I create requests with SQL parameters. It I set a DateTime parameter to the value DateTime.Now, what will my request look like ?

UPDATE table SET date = "2010/12/20 10:25:00";

or

UPDATE table SET date = GETDATE();

In the first case I'm sure that every record will be set to the exact same time. In the second case it depends on how the DBMS processes the request. Which leads me to the second question : does SQL Server set the same date and time when updating a large table with NOW() ?

EDIT : replaced NOW() (which doesn't exist in SQL Server) by GETDATE().

Sql Server Solutions


Solution 1 - Sql Server

In SQL you need to use GETDATE():

UPDATE table SET date = GETDATE();

There is no NOW() function.


To answer your question:

In a large table, since the function is evaluated for each row, you will end up getting different values for the updated field.

So, if your requirement is to set it all to the same date I would do something like this (untested):

DECLARE @currDate DATETIME;
SET @currDate = GETDATE();

UPDATE table SET date = @currDate;

Solution 2 - Sql Server

An alternative to GETDATE() is CURRENT_TIMESTAMP. Does the exact same thing.

Solution 3 - Sql Server

Use GETDATE()

> Returns the current database system > timestamp as a datetime value without > the database time zone offset. This > value is derived from the operating > system of the computer on which the > instance of SQL Server is running.

UPDATE table SET date = GETDATE()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThibault WitzigView Question on Stackoverflow
Solution 1 - Sql ServerOdedView Answer on Stackoverflow
Solution 2 - Sql ServerDon SimonView Answer on Stackoverflow
Solution 3 - Sql ServerAdriaan StanderView Answer on Stackoverflow