如何根据另一个值的范围使用预定义值

时间:2013-09-06 15:53:25

标签: sql sql-server variables

废弃我原来的问题,因为这可能是一个更清晰的版本!

这就是我想要做的。目前我得到*'当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。'强调文本 *

declare @X int

SET @X=(
SELECT B.ID, 
Case
When Getdate() Between '2012-11-01 00:00' AND '2013-10-31 23:59' then 731
When Getdate() Between '2012-11-01 00:00' AND '2013-10-31 23:59' then 1096
END FROM  Booking B)


Select 
B.Created - @X AS 'Bookings date less X'
From Booking B

2 个答案:

答案 0 :(得分:2)

不确定你在那里尝试用第二位做什么,但这应该对你有所帮助(假设你使用的是SQL Server)......

declare @x integer;

set @x = case WHEN Getdate() Between '2012-11-01 00:00' AND '2013-10-31 23:59' then -731 when Getdate() Between '2013-11-01 00:00' AND '2014-10-31 23:59' then 1 end;

print @x

答案 1 :(得分:1)

如果我正确理解了您的问题,那么您正在寻找case statementvariable

DECLARE @X int

SELECT @X = 
    CASE WHEN Getdate() Between '2012-11-01 00:00' AND '2013-10-31 23:59' THEN -731
    ELSE
    CASE WHEN Getdate() Between '2013-11-01 00:00' AND '2014-10-31 23:59' THEN 1096
    ELSE
    NULL
    END

然后在随后的一些声明中:

CASE WHEN B.Created < @X THEN 'Hello' ELSE 'Not Hello' END