0
以下腳本計算減去其他特定時間間隔後的剩餘時間間隔。扣除其他時間間隔後計算剩餘時間間隔(開始日期 - >結束日期)
最後我留下的間隙填補了空白。
這是我創建的腳本。有誰知道更好的方法來做到這一點?
SELECT * FROM SuspensionPeriod susPer WHERE id_document = 564148
DECLARE @idDocument BIGINT, @docBeginDate DATETIME, @docEndDate DATETIME
SET @idDocument = 564148
SELECT @docBeginDate = start_date, @docEndDate = end_date FROM Document md WHERE md.id_document = @idDocument
SELECT RowNum = Row_number() OVER(ORDER BY suspended_from), *
INTO #SuspensionPeriods
FROM SuspensionPeriod susPer WHERE susPer.id_document = @idDocument
DECLARE @MaxRownum INT
SET @MaxRownum = (SELECT Max(RowNum) FROM #SuspensionPeriods)
DECLARE @Iter INT
SET @Iter = (SELECT Min(RowNum) FROM #SuspensionPeriods)
DECLARE @intervalBegin DATETIME, @intervalEnd DATETIME
WHILE @Iter <= @MaxRownum
BEGIN
IF @Iter = 1
BEGIN
SET @intervalBegin = @docBeginDate
SELECT @intervalEnd = suspended_from FROM #SuspensionPeriods WHERE RowNum = @Iter
print dbo.fnFormatDate(@intervalBegin,'yyyy.MM.dd')
print dbo.fnFormatDate(@intervalEnd,'yyyy.MM.dd')
print '============================='
--SELECT @intervalBegin = suspended_until FROM #SuspensionPeriods WHERE RowNum = @Iter
--SELECT @intervalEnd = suspended_from FROM #SuspensionPeriods WHERE RowNum = @Iter + 1
--print dbo.fnFormatDate(@intervalBegin,'yyyy.MM.dd')
--print dbo.fnFormatDate(@intervalEnd,'yyyy.MM.dd')
--print '============================='
END
IF @Iter <> 1 AND @Iter <> @MaxRownum
BEGIN
SELECT @intervalBegin = suspended_until FROM #SuspensionPeriods WHERE RowNum = @Iter - 1
SELECT @intervalEnd = suspended_from FROM #SuspensionPeriods WHERE RowNum = @Iter
print dbo.fnFormatDate(@intervalBegin,'yyyy.MM.dd')
print dbo.fnFormatDate(@intervalEnd,'yyyy.MM.dd')
print '============================='
SELECT @intervalBegin = suspended_until FROM #SuspensionPeriods WHERE RowNum = @Iter
SELECT @intervalEnd = suspended_from FROM #SuspensionPeriods WHERE RowNum = @Iter + 1
print dbo.fnFormatDate(@intervalBegin,'yyyy.MM.dd')
print dbo.fnFormatDate(@intervalEnd,'yyyy.MM.dd')
print '============================='
END
IF @Iter = @MaxRownum
BEGIN
--SELECT @intervalBegin = suspended_until FROM #SuspensionPeriods WHERE RowNum = @Iter - 1
--SELECT @intervalEnd = suspended_from FROM #SuspensionPeriods WHERE RowNum = @Iter
--print dbo.fnFormatDate(@intervalBegin,'yyyy.MM.dd')
--print dbo.fnFormatDate(@intervalEnd,'yyyy.MM.dd')
--print '============================='
SELECT @intervalBegin = suspended_until FROM #SuspensionPeriods WHERE RowNum = @Iter
SELECT @intervalEnd = @docEndDate
print dbo.fnFormatDate(@intervalBegin,'yyyy.MM.dd')
print dbo.fnFormatDate(@intervalEnd,'yyyy.MM.dd')
print '============================='
END
-- run your operation here
SET @Iter = @Iter + 1
END
DROP TABLE #SuspensionPeriods
什麼是 「好」 是什麼意思?你已有的腳本有什麼問題?如果結果不正確,那麼您需要顯示一些示例數據並將腳本降低到顯示問題所需的最低限度,例如,上面的印刷品和評論是不相關的。 – Pondlife
簡短答案=是。在編程時非常線性(增加一個行號,因此可以像增加的while循環那樣完成,這是一個糟糕的sql邏輯,你想要一次完成所有的行),並且可能會切換到基於集合的,可能是一個語句。你需要給我們一些表格模式和一個你想要完成的東西的更好的想法,這裏沒有足夠的信息來給你寫一個例子。 – Twelfth