我正在尝试编写一个返回两个日期之间的记录的查询(每个日期都有TIME格式的截止值)。到目前为止,我有以下内容:
例如:
SELECT
T.CustomerName,
T.MoneyToTransfer
FROM dbo.[Transfer] T
WHERE T.CreatedDate BETWEEN '2016-05-10 03:00:00.0000000' AND '2016-05-11 03:00:00.0000000'
然而截止时间03:00:00.0000000只是我认为查询需要格式化的占位符 - 需要从存储为数据类型TIME的字段'Cutoff'中的另一个表'TransferSubscriber'中检索TIME。问题是表TransferSubscriber中的此Cutoff字段存储在LOCAL时间(以TIME数据类型)。我需要将此TIME转换为UTC,并将其放在比较的TIME部分(03:00:00.0000000)中的BETWEEN语句中。
我写了以下内容,将日期和时间变量连接成一个问题:
DECLARE @startDate DATE = (SELECT CONVERT(VARCHAR, '2016-07-13', 110))
DECLARE @Cutoff AS TIME(7) = (SELECT TOP 1 S.CutoffTime FROM Subscriber.dbo.TransferSubscriber S WHERE ID = 10)
DECLARE @CutoffUTC TIME = (SELECT DATEADD(second,DATEDIFF(second, GETDATE(), GETUTCDATE()), @Cutoff))
DECLARE @StartDateFinal = @startDate + @CutoffUTC
@StartDateFinal抛出错误:
“操作数数据类型日期对于添加运算符无效。”
我确信有更好的方法可以将本地TIME转换为UTC时间,并使用它来比较两个DATETIME字段。
任何帮助都会很棒!
答案 0 :(得分:0)
尝试以下方法,
DECLARE @startDate DATE = (SELECT CONVERT(VARCHAR, '2016-07-13', 110))
DECLARE @Cutoff AS TIME(7) = (SELECT TOP 1 S.CutoffTime FROM Subscriber.dbo.TransferSubscriber S WHERE ID = 10)
DECLARE @CutoffUTC TIME = (SELECT DATEADD(second,DATEDIFF(second, GETDATE(), GETUTCDATE()), @Cutoff))
DECLARE @StartDateFinal DATETIME2
SELECT @StartDateFinal=CAST(CAST(@startDate AS VARCHAR) +' '+ CAST(@CutoffUTC AS VARCHAR) AS DATETIME2)
SELECT @StartDateFinal
希望它有所帮助。