在脚本中使用declare创建视图。程序和功能不起作用

时间:2018-02-09 14:40:58

标签: sql-server procedure

我无法使用声明创建视图。 我甚至试图创建程序,但我发现我不能用程序创建视图。我认为同样的功能。我唯一能想到的就是避免申报。我怎么能找到方法?我需要有视图表(为了能够在将来看到它们的功能,我无法从存储过程中看到它)

declare @T as table (
    Name nvarchar(100)
    , OBJECTID varchar(50)
    , started_working datetime
    ,STOPFROM datetime
    ,STARTDATE datetime
    ,STOPDATE datetime
    ,MODIFIEDDATETIME datetime
    ,START_STOP int
    ,STARTDESCRIPTION nvarchar(300)
    ,STOPDESCRIPTION nvarchar(300)
    ,wattage nvarchar (50)
    ,purpose nvarchar(300)
    ,location nvarchar(300)
    ,finished_working datetime
    ,oldDiff int
)

insert into @T
select 
    NAME
    ,OBJECTID
    ,STOPTO
    ,STOPFROM
    ,STARTDATE
    ,STOPDATE
    ,MODIFIEDDATETIME
    ,START_STOP
    ,STARTDESCRIPTION
    ,STOPDESCRIPTION
    ,wattage
    ,purpose
    ,location
    ,next_stopfrom
    ,diff
    FROM [MicrosoftDynamicsAX].[dbo].[mroobjectengineworkinghours]

 ;with rcte as (
    select
        *, started_working2 = started_working
        , next_date = cast(dateadd(dd, 1, started_working) as date), 1 step
    from 
        @T
    union all
    select
        Name,OBJECTID, started_working,STOPFROM,STARTDATE,STOPDATE,MODIFIEDDATETIME,START_STOP,STARTDESCRIPTION
    ,STOPDESCRIPTION,wattage
    ,purpose
    ,location, finished_working,oldDiff
        , cast(next_date as datetime)
        , dateadd(dd, 1, next_date), step + 1
    from
        rcte
    where
        next_date < finished_working
)

select
    Name,OBJECTID, started_working,STOPFROM,STARTDATE,STOPDATE,MODIFIEDDATETIME,START_STOP,STARTDESCRIPTION
    ,STOPDESCRIPTION,wattage
    ,purpose
    ,location,oldDiff, started_working2, finished_working
    , right(replace(str(diff / 60), ' ', 0), 2) + ':' + right(replace(str(diff % 60), ' ', 0), 2) hours_worked
from (
    select
        Name,OBJECTID, started_working,STOPFROM,STARTDATE,STOPDATE,MODIFIEDDATETIME,START_STOP,STARTDESCRIPTION
    ,STOPDESCRIPTION,wattage
    ,purpose
    ,location,oldDiff
        , case 
            when step = 1 then started_working 
            else started_working2 
        end started_working2
        , case 
            when step = max(step) over (partition by Name, started_working) 
            then finished_working else next_date 
        end finished_working
    from
        rcte
) t
cross apply (select datediff(mi, started_working2, finished_working) diff) ca
OPTION (MAXRECURSION 0);

1 个答案:

答案 0 :(得分:0)

我同意肖恩·兰格的观点。

为什么不在你的cte中直接调用表格?

如:

;with rcte as ( 
select *
     , started_working2 = started_working 
     , next_date = cast(dateadd(dd, 1, started_working) as date)
     , 1 step 
  from [MicrosoftDynamicsAX].[dbo].[mroobjectengineworkinghours] ...