2013-09-16 40 views
-2

我有一个存储过程对于在执行这个我确切出越来越手动枢转而手动枢转转换为自动枢轴没有得到任何值

ALTER procedure [dbo].[performancepivot] (
    @startdate datetime, 
    @enddate datetime 
) as begin 

    set nocount on 
    declare @date1 nvarchar(100)=convert(varchar, @startdate+'00:00:00.000',120), 
      @date2 nvarchar(100)= convert(varchar, @enddate+'23:59:59.000',120); 

    with cte as (select l.LocName, v.Vtype,sum(datediff(mi, t.DelDate, t.Paydate)) as TotalDiff, 
      dbo.testfunctionstacknew(convert(decimal(10,1),avg(convert(numeric(18,2), datediff(ss, t.Paydate, t.DelDate))))) as Average 
     from Transaction_tbl as t 
      left join VType_tbl as v on t.vtid = v.vtid 
      left join Location_tbl as l on t.Locid = l.Locid 
     where t.Locid in (select t1.Locid from Transaction_tbl as t1) 
      and t.dtime between @date1 and @date2 
      and t.Status = 5 
     group by v.Vtype, l.LocName, l.Locid) 

    select c.LocName, 
     max(case when c.Vtype = 'Normal' then Average end) as Normal, 
     max(case when c.Vtype = 'Vip' then Average end) as Vip, 
     max(case when c.Vtype = 'VVip' then Average end) as VVip, 
     max(case when c.Vtype = 'Pass' then Average end) as Pass, 
     max(case when c.Vtype = 'Staff' then Average end) as Staff 
    from cte as c group by c.LocName order by c.LocName 
end 

put..i不想枢轴manually..so我尝试写存储过程“自动旋转” .. 我试着写存储过程是这样的:

ALTER procedure [dbo].[ParkingSummary1] 
    @startdate nvarchar(100), @enddate nvarchar(100) as 
    begin 
     declare @date1 nvarchar(100) = convert(varchar, @startdate+' 00:00:00.000', 120) 
     declare @date2 nvarchar(100) = convert(varchar, @enddate+' 23:59:59.000', 120) 
     DECLARE @cols AS NVARCHAR(MAX),@query AS NVARCHAR(MAX) 
     select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Vtype) from VType_tbl 
     FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,'') 
     set @query = 'SELECT LocName, ' + @cols + ' from (select l.LocName,Vtype from Transaction_tbl t join VType_tbl v on t.vtid = v.vtid join dbo.Location_tbl l on t.locid=l.Locid where dtime between '''+ @date1 +''' and '''+ @date2 +''' 
     and Status = 5) d pivot (count(Vtype) for Vtype in (' + @cols + ')) p ' 
     print @query 
    end 

但在执行此存储过程我没有得到任何value..i知道什么毛病此存储过程 WH在我的第二个存储过程错误..如果任何人知道请帮我找出

+0

请修复格式。 – Kermit

+0

虽然给代码正确..显示错误.. – user2747546

+0

我无法读取第一段代码。它太混乱了,需要更好地格式化。 –

回答

0

正如你所写,你的存储过程不会执行它建立的动态SQL查询。请更换print @query,或只是追加,下面的语句:

EXECUTE (@query); 

或者这一个:

EXECUTE sp_executesql @query; 

欲了解更多信息,请参见: