我正在为此功能获得正确的输出。 datediff是否仅计算同月的天数差异? 当我以2015年1月1日及以后的形式通过约会时。它总是给我发回0 = /我错过了我的逻辑或语法中的东西吗?
CREATE FUNCTION dbo.CanPolicy
(
@ReservationID int,
@CancellationDate date
)
RETURNS smallmoney
AS
BEGIN
DECLARE @DepositPaid smallmoney
SET @DepositPaid = (SELECT ResDepositPaid
FROM Reservation
WHERE ReservationID = @ReservationID)
DECLARE @ResDate date
SET @ResDate = (SELECT ResDate
FROM Reservation
WHERE ReservationID = @ReservationID)
DECLARE @CanceledDaysAhead int
SET @CanceledDaysAhead = DATEDIFF(day, @ResDate, @CancellationDate)
DECLARE @result smallmoney
SET @result = 0
SET @result = CASE WHEN @CanceledDaysAhead > 30 THEN 0
WHEN @CanceledDaysAhead BETWEEN 14 AND 30 THEN @DepositPaid * 0.25 + 25
WHEN @CanceledDaysAhead BETWEEN 8 AND 13 THEN @DepositPaid * 0.50 + 25
ELSE @DepositPaid
END
RETURN @result
END
GO
答案 0 :(得分:1)
不,DATEDIFF计算两者之间的日期。尝试:
SELECT DATEDIFF(day,{ts'2105-01-01 00:00:00'},{ts'2105-04-01 00:00:00'})
可能是日期格式问题......
您确定@ResDate设置正确吗?
编辑:CTE的新方法
DECLARE @ReservationID INT=123;
DECLARE @CancelationDate DATE=GETDATE();
WITH ReservationCTE AS
(
SELECT ResDepositPaid
,ResDate
FROM Reservation
WHERE ReservationID=@ReservationID --assuming that ReservationID is a unique key!
)
,ReservationCTEWithDateDiff AS
(
SELECT ReservationCTE.*
--EDIT: switched dates due to a comment by Me.Name
,DATEDIFF(DAY,@CancelationDate,ResDate) AS CanceledDaysAhead
FROM ReservationCTE
)
SELECT CASE WHEN CanceledDaysAhead>30 THEN 0
WHEN CanceledDaysAhead BETWEEN 14 AND 30 THEN ResDepositPaid * 0.25 + 25
WHEN CanceledDaysAhead BETWEEN 8 AND 13 THEN ResDepositPaid * 0.50 + 25
ELSE ResDepositPaid END AS MyReturnValue
FROM ReservationCTEWithDateDiff
答案 1 :(得分:1)
我认为你的功能的正确和简短版本就是这个 - 请试一试:
CREATE FUNCTION dbo.CanPolicy
(
@ReservationID int,
@CancellationDate date
)
RETURNS smallmoney
AS
BEGIN
DECLARE @DepositPaid smallmoney,
@CanceledDaysAhead int
SELECT @DepositPaid = ResDepositPaid,
@CanceledDaysAhead = DATEDIFF(DAY,ResDate,@CancellationDate)
FROM Reservation
WHERE ReservationID = @ReservationID
RETURN CAST(CASE WHEN @CanceledDaysAhead > 30 THEN 0 ELSE
CASE WHEN @CanceledDaysAhead BETWEEN 14 AND 30 THEN @DepositPaid * 0.25 + 25 ELSE
CASE WHEN @CanceledDaysAhead BETWEEN 8 AND 13 THEN @DepositPaid * 0.50 + 25 ELSE
@DepositPaid END END END AS smallmoney)
END
GO
主要问题是你的情况 - 当我认为阻止......
答案 2 :(得分:0)