我有一个场景,我必须匹配系统时间,但我必须将当前时间与sql server中预先设置的保存日期时间变量相匹配。
DECLARE @SyncDate AS DATETIME
DECLARE @SystemDate AS DATETIME
SELECT @SyncDate = dbo.TimeTable.auto_time
FROM dbo.TimeTable
'1900-01-01 03:00
SELECT @SystemDate = GETDATE()
我必须用当前日期和已保存的时间替换@SyncDate
,即:
2015-11-16 03:00
任何人都可以帮忙吗?
答案 0 :(得分:1)
您可以直接在SQL Server 2008+中将TIME
值添加到DATETIME
值。但对于SQL Server 2005,您可以使用DATETIME
和DATEADD
等DATEDIFF
操作:
对于SQL Server 2008:
DECLARE @SyncDate DATETIME = CAST('1900-01-01 03:00' AS DATETIME)
SELECT
CAST(CAST(GETDATE() AS DATE) AS DATETIME) + CAST(@SyncDate AS TIME)
对于SQL Server 2005:
DECLARE @SyncDate DATETIME
SET @SyncDate = CAST('1900-01-01 03:00' AS DATETIME)
SELECT
DATEADD(
MILLISECOND,
DATEDIFF(MILLISECOND, CAST(@SyncDate AS DATE), @SyncDate),
CAST(CAST(GETDATE() AS DATE) AS DATETIME)
)
答案 1 :(得分:1)
您可以使用:
DECLARE @SyncDate AS DATETIME = GETDATE();
DECLARE @SystemDate AS DATETIME = '1900-01-01 03:00' --saved time
SELECT DATEADD(day, DATEDIFF(day,'19000101',CAST(@SyncDate AS DATE)), CAST(CAST(@SystemDate AS TIME) AS DATETIME));
的 LiveDemo
强>
输出:
2015-11-16 03:00:00
如果保存时间始终为1900-01-01 hh:mm:ss
格式,您可以使用:
DECLARE @SyncDate AS DATETIME = GETDATE();
DECLARE @SystemDate AS DATETIME = '1900-01-01 03:00'
SELECT DATEADD(day, DATEDIFF(day,'19000101',CAST(@SyncDate AS DATE)), @SystemDate);
的 LiveDemo2
强>
答案 2 :(得分:0)
我已经完成了一个通用查询,即自由格式版本检查或版本依赖。
DECLARE @SyncDate AS DATETIME = '1900-01-01 03:00'
DECLARE @SystemDate AS DATETIME = GETDATE() ;
SELECT @SyncDate = DATEADD(dd, 0, DATEDIFF(dd, 0, @SystemDate))
+ CONVERT(VARCHAR(8), @SyncDate, 108)
SELECT @SyncDate
答案 3 :(得分:0)
在2020年为SqlServer 2016而来的人:
DECLARE @SyncDate DATETIME = CAST('1900-01-01 03:00' AS DATETIME)
SELECT
CAST(CAST(GETDATE() AS DATE) AS DATETIME) + CAST(@SyncDate AS DATETIME)
输出
2020-11-26 03:00:00.0
PS:查询于2020年11月26日进行。