简体   繁体   English

MS SQL 2014:将过程重写为CTE

[英]MS SQL 2014: Rewrite procedure into CTE

In MS SQL 2014 I've got a procedure that calculates years months and days in a way that from 5 years 14 months and 35 days I get 6 years 3 months and 5 days . 在MS SQL 2014中,我有一个计算年月日的过程,从5年14个月35天,我得到6年3个月5天 Because I can use neither procedure (even temp) nor function in my code, I need that calculation into eg CTE. 因为我在代码中既不能使用过程(甚至临时)也不能使用函数,所以我需要将该计算结果放入CTE中。 Can anyone help? 有人可以帮忙吗?

CREATE PROCEDURE #YearsMonthsDaysSum @EmpId INT
AS
BEGIN
DECLARE @Years INT, @Months INT, @Days INT
SELECT @Years=Years, @Months=Months, @Days=Days FROM #Table1 WHERE EmpId=@EmpId
IF @Days<0
BEGIN
    SET @Months=@Months-(1-CAST(@Days/30 as INT))
    SET @Days=@Days+30*(1-CAST(@Days/30 as INT))
END
IF @Months<0
BEGIN
    SET @Years=@Years-(1-CAST(@Months/12 as INT))
    SET @Months=@Months+12*(1-CAST(@Months/12 as INT))
END
IF(@Days>30)
BEGIN
    SET @Months=@Months+CAST(@Days/30 as INT)
    SET @Days=@Days%30
END
IF(@Months>=12)
BEGIN
    SET @Years=@Years+CAST(@Months/12 as INT)
    SET @Months=@Months%12
END

SELECT EmpId=@EmpId, Years=@Years, Months=@Months, Days=@Days
END

It would be easier to first calculate the total number of days, then get back to years,months and days. 首先计算天总数,然后返回到年,月和天,会更容易。

declare @empid int = 1
Declare @table1 table (empid int, years int, months int, [days] int)
insert into @table1 values (1,5,14,35)

;with YearsMonthsDaysSum_cte as
(
    select days/(30*12) years,(days%(30*12))/30 months,days%30 [days]
    from (
        select  [days] + months * 30 + years * 30*12 [days]
        from @table1) x
    )

select * from YearsMonthsDaysSum_cte

Using CROSS APPLY for in-line calculations eliminates CTE. 使用CROSS APPLY进行在线计算可消除CTE。 Just 只是

SELECT EmpId, step2.Years, step2.Months, step2.Days
    FROM #Table1 t
    CROSS APPLY (
      SELECT totaldays = [days] + months * 30 + years * 30*12 [days]
    ) step1 
    CROSS APPLY (
      SELECT 
        years = totaldays/(30*12), 
        months = totaldays%(30*12))/30,
        [days] = totaldays%30 
    ) step2
  -- JOIN, WHERE or any other Sql follows
;

More steps can be added for complex calculations, leap years for example. 可以为复杂的计算添加更多步骤,例如for年。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM