2015-10-14 95 views
0

我想根據CASE聲明選擇數據。示例如下CASE語句中可以有WHILE循環嗎?

select Id, name, address, 
     case when 
      department = CIS then @first 
      else @firstnew 
     end as "Date" 

這裏@first給出的應該是查詢下面

DECLARE @first date, @second date, @current date, @new date; 
SET @second='2015-12-15' 
SET @new='2015-08-10' 
SET @current = CONVERT(VARCHAR(10),GETDATE(),110) 
SET @first = '2015-08-15' 
WHILE @first <= @second 
BEGIN 
    SET @first = @new 
    WHILE @first <= @second 
    BEGIN 
     if @first >= @current 
     break; 
     SET @first = DATEADD(MONTH,1,@first) 
    END; 
    break; 
END; 

輸出是否可以使用上面的查詢輸出@first的值作爲第一SELECT語句的結果如果該部門等於CIS的情況?

+0

我相信你可以找到@First值,而那個醜陋while循環... –

+0

@Giorgi Nakeuri沒得到的正確的答案,這就是爲什麼我提出了另一個問題解釋我的senario – user2792602

+0

你應該編輯這個問題,而不是添加一個新的。你可以對答案發表評論,並詳細說明它有什麼問題。 –

回答

1

我覺得@firstnew等於DATEADD(MONTH, -1, DATEFROMPARTS(YEAR(@second), MONTH(@second), DAY(@new))),所以你的查詢可以是這樣的:

SELECT Id, name, address, 
    CASE WHEN department = 'CIS' THEN 
     @first 
    CASE WHEN @first > @second THEN 
     @first 
    CASE WHEN @new > @second THEN 
     @new 
    CASE WHEN DATEFROMPARTS(YEAR(@second), MONTH(@second), DAY(@new)) < @second THEN 
     DATEFROMPARTS(YEAR(@second), MONTH(@second), DAY(@new)) 
    ELSE 
     DATEADD(MONTH, -1, DATEFROMPARTS(YEAR(@second), MONTH(@second), DAY(@new))) 
    END AS [Date] 
...