执行数据透视存储过程时得到的预期错误

时间:2013-09-18 07:12:11

标签: sql sql-server

这是我的存储过程:

ALTER procedure [dbo].[performancepivot]   
    @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
                + '(select l.LocName
                          ,v.Vtype
                          ,[dbo].[testfunctionstacknew](CONVERT(decimal(10,1)
                                                        ,AVG(CONVERT(NUMERIC(18,2)
                                                        ,DATEDIFF(SS,t.Paydate,t.DelDate))))) as Average    
                    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
    exec sp_executesql @query;  
end

执行此操作时,我收到的错误如下:

SELECT LocName
      ,[Emaar Staff]
      ,[Lost Ticket]
      ,[Normal]
      ,[VIP]
      ,[VVIP]
      , -- This Comma was missing added by MBD edit
      (select l.LocName
             ,v.Vtype
             ,[dbo].[testfunctionstacknew](CONVERT(decimal(10,1)
                                          ,AVG(CONVERT(NUMERIC(18,2)
                                            ,DATEDIFF(SS,t.Paydate,t.DelDate))))) as Average
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 '2013-01-01 00:00:00.000' and '2013-08-01 23:59:59.000'  
            and Status = 5) d

      pivot  

      (count(Vtype) for Vtype in ([Emaar Staff],[Lost Ticket],[Normal],[VIP],[VVIP])) p 
  

Msg 102,Level 15,State 1,Line 8'p'附近的语法不正确。 (1   行(受影响)

我的存储过程出了什么问题?

1 个答案:

答案 0 :(得分:0)

您的查询遭遇结构和语法错误:

  1. 我迷失了,试图跟上已开启和关闭( )的数量。你应该开始考虑那个。
  2. 您无法在其他SELECT内使用嵌入式SELECT语句。嵌入式SELECT只能在FROMWHEREHAVING声明中使用。在您的查询中,子选择返回3个值,但您将它们引用为Average(一个值)
  3. 我强烈建议您直接编写存储过程,因为我可以看到您使用查询构造仅嵌入变量,而不是实际构建查询。您可以将查询编写为通常的存储过程,并将其用作SP变量。
  4. 我在您的查询中添加了一个缺少的逗号,请检查