使用条件在SQL中设置变量

时间:2013-11-27 13:07:38

标签: tsql variables

我正在制作一份报告,将年份分为下半年的上半年。它还会查看上一年的同一时间框架以显示比较。我正在尝试创建一些变量来确定正确的日期范围取决于我们当前的年份。

我遇到了if语句部分的问题,并且在第二个if语句中设置了2个变量。我看不出有什么不对劲。我知道我可以在客户端应用程序中传递变量并将其全部计算出来。我非常接近这项工作,我希望看到它的运作方式。

Declare @CurrDate as date set @CurrDate = convert(datetime,'27/04/2013',103)

Declare @ThisTimeLastYear as date set @ThisTimeLastYear  = dateadd(year,-1,@currdate)

Declare @LastYearCheck as date set @LastYearCheck  = convert(datetime,cast(30 as varchar) + '/' + cast(6 as varchar) + '/' + cast(DATEPART (year,@currdate)-1 as varchar) ,103)
Declare @SpringStartlastYear as date set @springStartlastYear = convert(datetime,'01/01/2012',103)
Declare @AutWinterStartLastYear as date set @AutWinterStartLastYear  = convert(datetime,cast(01 as varchar) + '/' + cast(07 as varchar) + '/' + cast(DATEPART (year,@currdate)-1 as varchar) ,103)

Declare @springEndLastYear as date
Declare @autumnEndLastYear as date 

if (@ThisTimeLastYear < @LastYearCheck)
   set @springEndLastYear = @ThisTimeLastYear 
  /*this year hasn't reached the autumn/winter season so move date ranges out of the way +20 year */
   set @AutWinterStartLastYear = DATEADD(year,20,@AutWinterStartLastYear)
   set @autumnEndLastYear = DATEADD(year,20,@autumnEndLastYear)
if (@ThisTimeLastYear > @LastYearCheck)
       set @springEndLastYear = @LastYearCheck
set @autumnEndLastYear = @ThisTimeLastYear

第二个if语句中的2个变量在它们不应该改变的时候会改变。

2 个答案:

答案 0 :(得分:0)

尝试: -

if (@ThisTimeLastYear < @LastYearCheck) begin
   set @springEndLastYear = @ThisTimeLastYear 
   /*this year hasn't reached the autumn/winter season so move date ranges out of the way +20 year */
   set @AutWinterStartLastYear = DATEADD(year,20,@AutWinterStartLastYear)
   set @autumnEndLastYear = DATEADD(year,20,@autumnEndLastYear)
end
if (@ThisTimeLastYear > @LastYearCheck) begin
    set @springEndLastYear = @LastYearCheck
    set @autumnEndLastYear = @ThisTimeLastYear
end

或(你的条件逻辑可能需要注意): -

if (@ThisTimeLastYear < @LastYearCheck) begin
   set @springEndLastYear = @ThisTimeLastYear 
   /*this year hasn't reached the autumn/winter season so move date ranges out of the way +20 year */
   set @AutWinterStartLastYear = DATEADD(year,20,@AutWinterStartLastYear)
   set @autumnEndLastYear = DATEADD(year,20,@autumnEndLastYear)
end else begin
    set @springEndLastYear = @LastYearCheck
    set @autumnEndLastYear = @ThisTimeLastYear
end

答案 1 :(得分:0)

你可以使用begin / end,这里有另一种选择:在tsql中你可以在同一个命令中填写几个变量,如下所示:

SELECT 
   @springEndLastYear = @ThisTimeLastYear,
   @AutWinterStartLastYear = DATEADD(year,20,@AutWinterStartLastYear),
   @autumnEndLastYear      = DATEADD(year,20,@autumnEndLastYear)
WHERE @ThisTimeLastYear < @LastYearCheck
SELECT 
   @springEndLastYear = @LastYearCheck,
   @autumnEndLastYear = @ThisTimeLastYear
WHERE @ThisTimeLastYear >= @LastYearCheck