-3

This is my stored procedure:

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

While executing this, I am getting Error like this:

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 Incorrect syntax near 'p'. (1 row(s) affected)

What is wrong with my stored procedure?

4

1 回答 1

0

您的查询存在结构和语法错误:

  1. 我迷路了,试图跟上打开和关闭的数量( )。你应该开始看那个。
  2. 您不能SELECT在其他SELECT. EmbeddedSELECT只能在FROM, WHEREorHAVING语句中使用。在您的查询中,子选择返回 3 个值,但您将它们引用为Average(一个值)
  3. 我强烈建议您直接编写存储过程,因为我可以看到您使用查询构造仅嵌入变量,而不是实际构建查询。您可以将查询编写为通常的存储过程,并将它们用作 SP 变量。
  4. 我在您的查询中添加了一个缺少的逗号,请检查
于 2013-09-18T09:03:31.500 回答