I need to set the hours, minutes and seconds in a certain datetime column to 00:00:00.0 after copying datetime values to it from another column.
In the table assignments
I have a datetime column activation_date
, into which I just copied datetimes from another datetime column creation_date
for rows that have null
as their activation_date
values. Both columns are in the same table. With the following:
UPDATE assignments
SET activation_date = creation_date
WHERE activation_date IS NULL;
Now, the hours, minutes and seconds in the activation_date
column need to be always 0:00:00.0, which isn't the case in the creation_date
values.
For example: A copied value is 2015-10-08 12:09:45.743
, but I want it to be 2015-10-08 00:00:00.0
in its new home, which is the activation_date
column.
I found out, that there's a function in SQL Server 2008 and above for this, called
SELECT CONVERT(Date, GETDATE())
As a complete SQL noob that I am, I can do the selection with said conversion as follows:
SELECT CONVERT(date, activation_date) AS activation_date
FROM assignments
Now, being a mere selection, this of course doesn't change anything. How I'm supposed to use this function in a UPDATE and SET manner, is beyond me. Any help is appreciated. Thank you.
Since you are using SQL 2012 version, how about use the FORMAT
function and do something like this ?
SELECT FORMAT(@date, 'yyyy-MM-dd 00:00:00.0')
result will be something like below:
result: 2016-02-16 00:00:00.0
And then your update will be something like below:
UPDATE assignments
SET activation_date = FORMAT(creation_date, 'yyyy-MM-dd 00:00:00.0')
WHERE activation_date IS NULL;
For some format reference , i forgot the link where i found this, but i've saved this on my SQL snippets so i am sharing you the below different formats that you can use :)
/*
FORMAT(). In my mind, this single function is one of the hands-down best new features of
SQL Server 2012, simply because the functionality that it provides has been so sorely needed
for so long. And for .NET developers, the immediate and obvious benefits of this new function
should be readily apparent just by looking at Figure 6. Another thing that I like about the new
FORMAT() function is that it represents an additional influx of CLR functionality directly into
T-SQL -- something that I hope to see more of in the future.
*/
SELECT
FORMAT(GETDATE(), 'yyyy-MM-dd') AS [ISO Formatted Date],
FORMAT(GETDATE(), 'yyyy-MM-dd hh:mm:ss') AS [Full ISO],
FORMAT(GETDATE(), 'MMMM dd, yyyy') AS [Long-hand Date (EN)],
FORMAT(GETDATE(), 'MMMM dd, yyyy', 'fr-FR') AS [French Date],
FORMAT(22.7, 'C', 'en-US') AS [US Currency],
FORMAT(22.7, 'C', 'en-GB') AS [UK Currency],
FORMAT(99 * 2.226, '000.000') AS [Padded Decimal],
FORMAT(12345678, '0,0') AS [Finally: Commas in Large Numbers]
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.