我可以在CASE语句中使用WHILE循环吗?

时间:2015-10-14 16:46:51

标签: sql-server sql-server-2008 sql-server-2014

我想根据CASE语句选择数据。示例如下:

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;

如果部门等于CIS的情况,是否可以使用上述查询输出@first的值作为第一个SELECT语句的结果?

1 个答案:

答案 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]
...