我有一个存储过程,从2个不同的服务器上提取数据,如下所示:
SELECT
LocalDB.Record_ID,
LocalDB.Total/1440 as TotalTime,
((REMOTE_ACTIVE.Time_Adjusted) - (REMOTE_ACTIVETimes.CALCTimeSec)) as TimeLeft,
LocalDB.isManualEntry
FROM LocalDatabase.dbo.Records LocalDB left join
[RemoteServer].[Reporting].[dbo].[ActiveWO] REMOTE_ACTIVE ON
LocalDB.WO_ID = REMOTE_ACTIVE.[PO_ID]
left join [RemoteServer].[Reporting].[dbo].[ActiveWOTimes] REMOTE_ACTIVETimes ON
LocalDB.WO_ID = REMOTE_ACTIVETimes.[PO_ID]
可能发生的情况是,有时“TimeLeft”值可能为0.当发生这种情况时,我想用
之类的内容替换该值IF(TimeLeft is 0 or null)
(getdate() - LocalDB.CreatedDate) as TimeElapsed
问题是,我不确定如何实施这样的IF声明,或者甚至是否可能。
答案 0 :(得分:2)
只需添加case
声明:
SELECT LocalDB.Record_ID,
LocalDB.Total/1440 as TotalTime,
(case when REMOTE_ACTIVE.Time_Adjusted - REMOTE_ACTIVETimes.CALCTimeSec <> 0
then REMOTE_ACTIVE.Time_Adjusted - REMOTE_ACTIVETimes.CALCTimeSec
else getdate() - LocalDB.CreatedDate
end) as TimeLeft,
LocalDB.isManualEntry
FROM LocalDatabase.dbo.Records LocalDB left join
[RemoteServer].[Reporting].[dbo].[ActiveWO] REMOTE_ACTIVE
ON LocalDB.WO_ID = REMOTE_ACTIVE.[PO_ID] left join
[RemoteServer].[Reporting].[dbo].[ActiveWOTimes] REMOTE_ACTIVETimes
ON LocalDB.WO_ID = REMOTE_ACTIVETimes.[PO_ID];
我在问题中假设TimeElapsed
替代TimeLeft
。
答案 1 :(得分:0)
您可以使用子查询
Select RecordID,TotalTime,TimeLeft,IsManualEntry,
CASE WHEN TimeLeft=0 OR TimeLeft is null THEN DATEDIFF(day, GETDATE(), CreationDate)
ELSE CreationDate END AS TimeElapsed,
FROM (
SELECT LocalDB.CreatedDate As CreationDate
LocalDB.Record_ID as RecordID,
LocalDB.Total/1440 as TotalTime,
((REMOTE_ACTIVE.Time_Adjusted) - (REMOTE_ACTIVETimes.CALCTimeSec)) as TimeLeft,
LocalDB.isManualEntry as IsManualEntry
FROM LocalDatabase.dbo.Records LocalDB left join
[RemoteServer].[Reporting].[dbo].[ActiveWO] REMOTE_ACTIVE ON
LocalDB.WO_ID = REMOTE_ACTIVE.[PO_ID]
left join [RemoteServer].[Reporting].[dbo].[ActiveWOTimes]
REMOTE_ACTIVETimes ON
LocalDB.WO_ID = REMOTE_ACTIVETimes.[PO_ID]
) Z
有关DATEDIFF
的更多信息