我需要在将日期时间值从另一列复制到某个日期时间列时将小时,分钟和秒设置为00:00:00.0。
在表assignments
中,我有一个日期时间列activation_date
,我刚从其他日期时间列creation_date
中复制了日期时间列null
作为其activation_date
的行1}}值。两列都在同一个表中。有以下内容:
UPDATE assignments
SET activation_date = creation_date
WHERE activation_date IS NULL;
现在,activation_date
列中的小时,分钟和秒必须始终为0:00:00.0,而creation_date
值中的情况并非如此。
例如:复制的值为2015-10-08 12:09:45.743
,但我希望它的新主页2015-10-08 00:00:00.0
为activation_date
列。
我发现,SQL Server 2008及更高版本中有一个函数,名为
SELECT CONVERT(Date, GETDATE())
作为一个完整的SQL noob,我可以通过以下转换进行选择:
SELECT CONVERT(date, activation_date) AS activation_date
FROM assignments
现在,作为一种选择,这当然不会改变任何事情。我应该如何以UPDATE和SET方式使用此功能,这超出了我的范围。任何帮助表示赞赏。谢谢。
答案 0 :(得分:1)
由于您使用的是SQL 2012版本,如何使用FORMAT
函数并执行类似的操作?
SELECT FORMAT(@date, 'yyyy-MM-dd 00:00:00.0')
结果将如下所示:
result: 2016-02-16 00:00:00.0
然后您的更新将如下所示:
UPDATE assignments
SET activation_date = FORMAT(creation_date, 'yyyy-MM-dd 00:00:00.0')
WHERE activation_date IS NULL;
对于某些格式参考,我忘记了我发现这个的链接,但我已将其保存在我的SQL片段中,所以我将分享您可以使用的以下不同格式:)
/*
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]
;