SQL内联变量赋值

时间:2012-05-25 18:05:25

标签: sql tsql variables

我有一个SQL语句,用于确定两个日期之间的天数。如果差异为负,则语句需要选择0.此语句有效,但我想知道是否可以将datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate)的值赋给@变量,因此我不必再调用它两次。

SELECT CASE 
WHEN datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) < 0  THEN 0
ELSE datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate)
END from ...

请不要问为什么我使用SQL而不是代码计算此值。

由于

5 个答案:

答案 0 :(得分:3)

您可以在计算中移动case语句,如下所示:

Select DateDiff("D", GetDate(), Case When YourColumn > GetDate() 
                                     Then YourColumn 
                                     Else GetDate() 
                                     End)

答案 1 :(得分:2)

你可以写一个更高级SELECT这样的东西。

SELECT CASE 
       WHEN diff_date < 0  THEN 0
       ELSE diff_date
       END 
FROM (
     SELECT datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) AS diff_date
     from ...
     )

答案 2 :(得分:1)

如果您选择多行,则无法将其分配给变量。在您的情况下,您可以使用派生表或CTE:

SELECT  Cols, 
        CASE 
        WHEN DiffDates < 0  THEN 0
        ELSE DiffDates
        END DiffDates
FROM (  SELECT Cols, datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) DiffDates
        FROM dbo.tblKBX_Reward) A

或者:

;WITH CTE AS
(
    SELECT Cols, datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) DiffDates
    FROM dbo.tblKBX_Reward
)

SELECT  Cols, 
        CASE 
        WHEN DiffDates < 0  THEN 0
        ELSE DiffDates
        END DiffDates
FROM CTE

答案 3 :(得分:1)

SELECT
  CASE WHEN daydiff < 0 THEN 0 ELSE daydiff END
FROM your tables/joins
CROSS APPLY (
  SELECT DATEDIFF(DAY, GETDATE(), dbo.tblKBX_Reward.validdate)
) x (daydiff)
WHERE …

答案 4 :(得分:0)

您可以使用CTE:

WITH cte_dateDiffs (RewardId, dateDiff) 
AS (
   SELECT RewardId, datediff("D",GETDATE(), validdate) FROM dbo.tblKBX_Reward
)
SELECT CASE 
   WHEN dd.dateDiff < 0 THEN 0 
   ELSE dd.dateDiff 
END
FROM dbo.tblKBX_Reward r
INNER JOIN cte_dateDiffs dd ON r.RewardId == dd.RewardId
...