将查询从PLSQL迁移到SQL SERVER

时间:2015-01-17 17:59:01

标签: sql-server tsql plsql

我有用PL / SQL编写的这部分代码

 if l_rec.sched_interval_type = 'DAYS' then    

      if l_max_date is null then     

        if l_rec.DAY_START_DAY is not null then     
           SELECT next_day(p_date, l_rec.DAY_START_DAY)    
           INTO l_start_date    
           FROM dual;    
        else    
           l_start_date := TRUNC(p_date);    
        end if;    

      else -- previous schedule recs exist...    

         if l_rec.DAY_START_DAY is not null then     
           SELECT next_day(GREATEST(l_max_date, p_date), l_rec.DAY_START_DAY)    
           INTO l_start_date    
           FROM dual;    
         else    
           l_start_date := l_max_date + l_rec.SCHED_AVAIL_DAYS;    
         end if;    

      end if;  

我需要将其转换为SQL SERVER

select 
CASE WHEN @l_max_date is null then    

    SELECT @l_start_date = CASE WHEN (SELECT sched_interval_type from #l_rec)  = 'DAYS' and @l_max_date is null and  @NextDayID is not null then    
    DATEADD(DAY, (DATEDIFF(DAY, ((@NextDayID + 5) % 7),@p_date) / 7) * 7 + 7, ((@NextDayID + 5) % 7))
          else CONVERT(DATETIME, CONVERT(DATE, @p_date)) end 
          from #l_rec

     ELSE -- previous schedule recs exist...    

  SELECT @l_start_date = CASE WHEN (SELECT sched_interval_type from #l_rec)  = 'DAYS' and @l_max_date is null and  @NextDayID is not null then    
          DATEADD(DAY, (DATEDIFF(DAY, ((@NextDayID + 5) % 7), [dbo].[greatest](@l_max_date, @p_date)) / 7) * 7 + 7, ((@NextDayID + 5) % 7))
              else @l_max_date+ (SELECT SCHED_AVAIL_DAYS from #l_rec) end 
              from #l_rec
         END 

我遇到case.. when的问题。有没有办法修改它?

2 个答案:

答案 0 :(得分:0)

在TSQL中,CASE 表达式返回某种类型的单个值。 (没有CASE语句。)您可以使用以下内容:

set @L_Start_Date = case
  when @L_Max_Date is null then
    ( select ... )
  when <some other condition> then
    ( some other expression that results in a single value )
  else
    ( expression that provides a default value )
  end

请注意,在SELECT中不会对变量赋值,只会将值返回CASE

答案 1 :(得分:0)

试试这个......

SELECT @l_start_date = 
        CASE 
            WHEN @l_max_date is null THEN
                CASE 
                    WHEN sched_interval_type = 'DAYS' AND @l_max_date IS NULL AND @NextDayID IS NOT NULL THEN DATEADD(DAY, (DATEDIFF(DAY, ((@NextDayID + 5) % 7),@p_date) / 7) * 7 + 7, ((@NextDayID + 5) % 7))
                    ELSE CONVERT(DATETIME, CONVERT(DATE, @p_date)) 
                END
            ELSE
                CASE 
                    WHEN sched_interval_type = 'DAYS' AND @l_max_date IS NULL AND @NextDayID IS NOT NULL THEN DATEADD(DAY, (DATEDIFF(DAY, ((@NextDayID + 5) % 7), [dbo].[greatest](@l_max_date, @p_date)) / 7) * 7 + 7, ((@NextDayID + 5) % 7))
                    ELSE @l_max_date+ SCHED_AVAIL_DAYS
                END
         END 
FROM #l_rec