存储过程:使用临时表减少代码重复

时间:2015-05-27 10:34:47

标签: sql sql-server stored-procedures refactoring temp-tables

在对我的存储过程进行了很多更改后,我认为它需要重新分解,主要是因为代码重复。如何克服这些重复:

IF @transExist > 0 BEGIN
    IF @transType = 1 BEGIN --INSERT
        SELECT
            a.dayDate,
            a.shiftName,
            a.limit,
            b.startTimeBefore,
            b.endTimeBefore,
            b.dayAdd,
            b.name,
            b.overtimeHours,
            c.startTime,
            c.endTime
        INTO 
            #Residence1
        FROM 
            #ShiftTrans a 
            RIGHT OUTER JOIN #ResidenceOvertime b
                ON a.dayDate = b.dayDate
            INNER JOIN ShiftDetails c
                ON c.shiftId = a.shiftId AND 
                c.shiftTypeId = b.shiftTypeId;

        SET @is_trans = 1;
    END ELSE BEGIN
        RETURN ;
    END
END ELSE BEGIN
    IF @employeeExist > 0 BEGIN
        SELECT
            a.dayDate,
            a.shiftName,
            a.limit,
            b.startTimeBefore,
            b.endTimeBefore,
            b.dayAdd,
            b.name,
            b.overtimeHours,
            c.startTime,
            c.endTime
        INTO 
            #Residence2
        FROM 
            #ShiftEmployees a 
            RIGHT OUTER JOIN #ResidenceOvertime b
                ON a.dayDate = b.dayDate
            INNER JOIN ShiftDetails c
                ON c.shiftId = a.shiftId AND 
                c.shiftTypeId = b.shiftTypeId;

            SET @is_trans = 0;
    END ELSE BEGIN
        RETURN;
    END
END;

IF @is_trans = 1 BEGIN
    WITH CTE_Residence_Overtime_trans AS (
        SELECT * FROM #Residence1
    )

    UPDATE t1
    SET 
        t1.over_time = t1.over_time 
          + CAST(RIGHT('0'+ CAST(overtimeHours as varchar(2)),2)
             +':00:00' As Time) 
          + CAST(RIGHT('0'+ CAST(@total_min  as varchar(2)),2)
             +':00:00' As Time),
        t1.day_flag = t1.day_flag + 'R1',
        t1.day_desc = 'R::' 
          + CTE_Residence_Overtime_trans.shiftName +'[ '
          + CTE_Residence_Overtime_trans.name +' ]'
    FROM 
        rr_overtime AS t1
        INNER JOIN CTE_Residence_Overtime_trans 
            ON t1.[trans_date] = CTE_Residence_Overtime_trans.[dayDate]
    WHERE 
        t1.emp_num = @empNum;

    UPDATE rr_overtime 
    SET 
        over_time = CAST(RIGHT('0'+ CAST(0 as varchar(2)),2)+':00:00' As Time),
        day_flag = day_flag +'R2'
    WHERE 
        trans_date = @TomorrowDate AND 
        emp_num = @empNum;

END ELSE BEGIN
    WITH CTE_Residence_Overtime AS (
        SELECT * FROM #Residence2
    )

    UPDATE t1
    SET 
        t1.over_time = CAST(RIGHT('0'+ CAST(overtimeHours as varchar(2)), 2) 
          +':00:00' As Time)
        + CAST(RIGHT('0'+ CAST(@total_min  as varchar(2)),2)+':00:00' As Time),
        t1.day_flag = t1.day_flag + 'R1',
        t1.day_desc = 'R::' 
          + CTE_Residence_Overtime.shiftName +'[ '
          + CTE_Residence_Overtime.name +' ]'
    FROM 
        rr_overtime AS t1
        INNER JOIN CTE_Residence_Overtime 
            ON t1.[trans_date] = CTE_Residence_Overtime.[dayDate]
    WHERE 
        t1.emp_num = @empNum ;

    UPDATE rr_overtime 
    SET 
        over_time = CAST(RIGHT('0'+ CAST(0 as varchar(2)),2)+':00:00' As Time),
        day_flag = day_flag +'R2'
    WHERE 
        trans_date = @TomorrowDate AND 
        emp_num = @empNum;

END 

5 个答案:

答案 0 :(得分:5)

查看代码,看起来应该可行:

WITH CTE_Residence_Overtime_trans AS (
    SELECT
        a.dayDate,
        a.shiftName,
        a.limit,
        b.startTimeBefore,
        b.endTimeBefore,
        b.dayAdd,
        b.name,
        b.overtimeHours,
        c.startTime,
        c.endTime
    FROM
        ( 
            select dayDate, shiftName, limit
            from #ShiftTrans
            where (@transExist > 0 and @transType = 1)
        union all
            select dayDate, shiftName, limit 
            from #ShiftEmployees
            where (not (@transExist>0 and @transType=1)) and @employeeExist>0
        ) a
    JOIN #ResidenceOvertime b
        ON a.dayDate = b.dayDate
    JOIN ShiftDetails c
        ON c.shiftId = a.shiftId AND 
        c.shiftTypeId = b.shiftTypeId
)

UPDATE t1
SET 
    t1.over_time = t1.over_time 
      + CAST(CAST(overtimeHours as varchar(2))+':00:00' As Time) 
      + CAST(CAST(@total_min    as varchar(2))+':00:00' As Time),
    t1.day_flag = t1.day_flag + 'R1',
    t1.day_desc = 'R::' + CTE.shiftName +'[ ' + CTE.name +' ]'
FROM 
    rr_overtime AS t1
    INNER JOIN CTE_Residence_Overtime_trans CTE
        ON t1.[trans_date] = CTE.[dayDate]
WHERE 
    t1.emp_num = @empNum;

UPDATE rr_overtime 
SET 
    over_time = CAST('00:00:00' As Time),
    day_flag = day_flag +'R2'
WHERE 
    trans_date = @TomorrowDate AND 
    emp_num = @empNum;

这使得一个联合都选择了两个temp。表,但仅根据变量从正确的数据中提取数据,并将其用作更新的CTE。我还删除了外连接,因为该表也涉及内连接。

虽然这可以缩短代码,但它并不总是最好的方法,因为它可能会导致使用更复杂的查询计划,从而导致性能问题。

我还从时间转换中删除了右(2,...)函数,因为时间转换也没有导致零,最后一个只是固定00:00:00。

答案 1 :(得分:3)

创建临时表的代码看起来完全相同,所以我将它合并到了CTE中。更新中的代码存在细微差别,可以使用CASE语句处理。如果需要,可以将CASE语句移动到CTE

所以试一试:

IF @transExist > 0
BEGIN
  IF @transType <> 1 RETURN ELSE SET @is_trans = 1
END
ELSE
BEGIN  
  IF @employeeExist <= 0 RETURN ELSE SET @is_trans = 0
END

;WITH CTE_Residence_Overtime_trans
AS
(
      SELECT a.dayDate,a.shiftName,a.limit,b.startTimeBefore,b.endTimeBefore,b.dayAdd,b.name,b.overtimeHours,c.startTime,c.endTime
       FROM #ShiftTrans a RIGHT OUTER JOIN #ResidenceOvertime b
       ON a.dayDate = b.dayDate
       INNER JOIN ShiftDetails c
       ON c.shiftId = a.shiftId AND c.shiftTypeId = b.shiftTypeId;
)

UPDATE t1 
SET t1.over_time =  
    CASE 
    WHEN @Is_Trans = 1 THEN
        t1.over_time + CAST(RIGHT('0'+ CAST(overtimeHours  as varchar(2)), 2)+':00:00' As Time) +
        CAST(RIGHT('0'+ CAST(@total_min  as varchar(2)), 2)+':00:00' As Time) 
    ELSE
        CAST(RIGHT('0'+ CAST(overtimeHours  as varchar(2)), 2)+':00:00' As Time) +
       CAST(RIGHT('0'+ CAST(@total_min  as varchar(2)), 2)+':00:00' As Time)
    END,
    t1.day_flag = t1.day_flag + 'R1',
    t1.day_desc = 'R::' +CTE_Residence_Overtime_trans.shiftName +'[ '+ CTE_Residence_Overtime_trans.name +' ]'
FROM rr_overtime AS t1
INNER JOIN CTE_Residence_Overtime_trans 
ON t1.[trans_date] = CTE_Residence_Overtime_trans.[dayDate]
WHERE t1.emp_num = @empNum ;

UPDATE rr_overtime SET over_time = CAST(RIGHT('0'+ CAST(0 as varchar(2)), 2)+':00:00' As Time),
day_flag = day_flag +'R2'
WHERE trans_date = @TomorrowDate AND emp_num = @empNum;

答案 2 :(得分:2)

您可以尝试以下操作以避免重复。基本上首先创建临时表(我已经猜到了数据类型),然后只使用这个表作为插入,因为你正在使用它是否会成为一个或另一个插入到此。

如果你从表中选择*,那么你就不需要CTE,所以只需从表中直接打电话。由于该表仅包含来自一个选择或另一个的数据,并且字段名称相同等,我们可以仅使用一个更新,如果不再需要:

Create table #Residence (dayDate varchar(9), shiftName varchar(20), limit int, startTimeBefore time, endTimeBefore time, dayAdd int, name varchar(30), overtimeHours int, startTime time, endTime time)

IF @transExist > 0 

       BEGIN

        IF @transType = 1 --INSERT
           BEGIN
          Insert into #Residence
          SELECT a.dayDate,a.shiftName,a.limit,b.startTimeBefore,b.endTimeBefore,b.dayAdd,b.name,b.overtimeHours,c.startTime,c.endTime
           FROM #ShiftTrans a RIGHT OUTER JOIN #ResidenceOvertime b
           ON a.dayDate = b.dayDate
           INNER JOIN ShiftDetails c
           ON c.shiftId = a.shiftId AND c.shiftTypeId = b.shiftTypeId;
           END
         ELSE
           BEGIN
           RETURN ;
           END
       END

  ELSE
     BEGIN

        IF @employeeExist > 0
            BEGIN
            Insert into #Residence
            SELECT a.dayDate,a.shiftName,a.limit,b.startTimeBefore,b.endTimeBefore,b.dayAdd,b.name,b.overtimeHours,c.startTime,c.endTime
            FROM #ShiftEmployees a RIGHT OUTER JOIN #ResidenceOvertime b
            ON a.dayDate = b.dayDate
            INNER JOIN ShiftDetails c
            ON c.shiftId = a.shiftId AND c.shiftTypeId = b.shiftTypeId;
            END
        ELSE
           BEGIN
             RETURN ;
           END
     END;

    UPDATE t1 
    SET t1.over_time = t1.over_time + CAST(RIGHT('0'+ CAST(overtimeHours  as varchar(2)), 2)+':00:00' As Time) +
    CAST(RIGHT('0'+ CAST(@total_min  as varchar(2)), 2)+':00:00' As Time),
    t1.day_flag = t1.day_flag + 'R1',
    t1.day_desc = 'R::' +R.shiftName +'[ '+ R.name +' ]'

    FROM rr_overtime AS t1
    INNER JOIN #Residence R
    ON t1.[trans_date] = R.[dayDate]
    WHERE t1.emp_num = @empNum ;

    UPDATE rr_overtime SET over_time = CAST(RIGHT('0'+ CAST(0 as varchar(2)), 2)+':00:00' As Time),
    day_flag = day_flag +'R2'
    WHERE trans_date = @TomorrowDate AND emp_num = @empNum;

答案 3 :(得分:2)

尝试使用动态查询

在插入查询中,只有from表的不同取决于条件,对吗? 所以使用这样的东西

DECLARE @FromTable NVARCHAR(250)
IF @transExist > 0 BEGIN
IF @transType = 1 BEGIN --INSERT
    SELECT @FromTable = '#ShiftTrans'
    SET @is_trans = 1;
END ELSE BEGIN
    RETURN ;
END
END ELSE BEGIN
IF @employeeExist > 0 BEGIN

        SELECT @FromTable = '#ShiftEmployees'
        SET @is_trans = 0;
END ELSE BEGIN
    RETURN;
END
END;

DECLARE @DynamicQuery NVARCHAR(MAX) = 'SELECT
        a.dayDate,
        a.shiftName,
        a.limit,
        b.startTimeBefore,
        b.endTimeBefore,
        b.dayAdd,
        b.name,
        b.overtimeHours,
        c.startTime,
        c.endTime
    INTO 
        #Residence1
    FROM 
        '+@FromTable+' a 
        RIGHT OUTER JOIN #ResidenceOvertime b
            ON a.dayDate = b.dayDate
        INNER JOIN ShiftDetails c
            ON c.shiftId = a.shiftId AND 
            c.shiftTypeId = b.shiftTypeId'


EXECUTE (@DynamicQuery)

同样为更新部分创建动态查询...

Thejus T V

答案 4 :(得分:2)

第一部分是使用UNION ALL组合#Trans和#Employee。但是,因为你仍然需要区分两者才能做到

t1.over_time = 
    t1.over_time   --<------------- One is cumalative add and the other isn't
    + CAST(RIGHT('0'+ CAST(overtimeHours as varchar(2)),2)
        +':00:00' As Time) 
    + CAST(RIGHT('0'+ CAST(@total_min  as varchar(2)),2)
        +':00:00' As Time),

代表Trans和

t1.over_time = 
    CAST(RIGHT('0'+ CAST(overtimeHours as varchar(2)), 2) 
        +':00:00' As Time)
    + CAST(RIGHT('0'+ CAST(@total_min  as varchar(2)),2)
        +':00:00' As Time),

对于Employee,我在CTE中添加了EmployeeType列。另外,对 rr_datatype 表中的目标数据类型做了一些假设。如果是,实际上是TIMEDATETIME或其他变体,则应使用DATEADD函数。 MSDN page here ..

最后,如果您只打算更新第一个UPDATE中涉及的那些记录而不是尝试更新整个表,那么第二个UPDATE语句也可以合并到第一个; WITH TransAndEmployee AS ( SELECT 'T' AS EmployeeType, dayDate, shiftName, limit FROM #ShiftTrans UNION ALL SELECT 'E' AS EmployeeType, dayDate, shiftName, limit FROM #ShiftEmployees ), PoundOvertime AS ( SELECT * FROM TransAndEmployee a RIGHT OUTER JOIN #ResidenceOvertime b ON a.dayDate = b.dayDate INNER JOIN ShiftDetails c ON c.shiftId = a.shiftId AND c.shiftTypeId = b.shiftTypeId; ) UPDATE ot SET over_time = DATEADD(mi,@total_min, DATEADD(hh,overtimeHours,CASE WHEN EmployeeType = 'T' THEN over_time ELSE '0:00' END) ), day_flag = day_flag + 'R1', day_desc = 'R::' + CTE_Residence_Overtime_trans.shiftName + '[ ' + CTE_Residence_Overtime_trans.name + ' ]' FROM rr_overtime ot INNER JOIN PoundOvertime p ON ot.[trans_date] = p.[dayDate] WHERE ot.emp_num = @empNum UPDATE rr_overtime SET over_time = CAST('00:00:00' As Time), -- You can probably do over_time = '00:00' if over_time is TIME day_flag = day_flag +'R2' WHERE trans_date = @TomorrowDate AND emp_num = @empNum; 语句中。 / p>

+ CAST(RIGHT('0'+ CAST(@total_min  as varchar(2)),2)
    +':00:00' As Time),

我做的另一个假设......下面看起来有点奇怪。我假设你试图添加“分钟”......但是这个字符串的操作似乎是将它添加到几个小时。我“纠正”了......让我知道这是不是很糟糕的假设。

results