Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a DateTime database field to "Now"

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

like image 876
Thibault Witzig Avatar asked Dec 20 '10 09:12

Thibault Witzig


People also ask

How do I get datetime now in SQL?

SQL Server GETDATE() Function The GETDATE() function returns the current database system date and time, in a 'YYYY-MM-DD hh:mm:ss.

How do I assign a current date to a column in SQL?

To update with the current date and time: UPDATE table_name SET date_field = CURRENT_TIMESTAMP; To update with a specific date value: UPDATE table_name SET date_field = 'YYYY-MM-DD HH:MM:SS.

How can I update a datetime field in SQL?

Firstly we take a table in which we want to update date and time fields. If you want to change the first row which id is 1 then you should write the following syntax: UPDATE table. SET EndDate = '2014-03-16 00:00:00.000'


1 Answers

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; 
like image 184
Oded Avatar answered Oct 10 '22 03:10

Oded