2012-10-24 40 views
0

我試圖用一個case語句設置變量值來確定財政年度,取決於一個月,但我得到財政年度Null值返回:牛逼SQL的使用情況下,當在參數

declare 
@Costcentre varchar(50) 
,@dt date 
,@dty int 
,@dtm int 

select @Costcentre = 'CAM' 
SELECT @dt = '2012-09-30' 
select @dtm = DATEPART(month,@dt) 
select 
@dty = case when @dtm between 4 and 12 then DATEPART(year,@dt) + 1 end 
,@dty = case when @dtm between 1 and 3 then DATEPART(year,@dt) end 


select @dty 

回答

2

你只需要分配@dty一次:

select @dty = case 
    when @dtm between 4 and 12 then DATEPART(year,@dt) + 1 
    when @dtm between 1 and 3 then DATEPART(year,@dt) 
end 

否則,你只是覆蓋@dty如果@dtm不是1和3之間