-3

我有一个这样的存储过程:

ALTER PROCEDURE [dbo].[ParkingDeatailsReportnew] 
 @startdate NVARCHAR(100),
  @enddate NVARCHAR(100)AS BEGINDECLARE  @cols AS NVARCHAR(MAX) , @query AS NVARCHAR(MAX)
 SELECT @cols = STUFF((  SELECT DISTINCT ',' + QUOTENAME(Vtype)
  FROM dbo.VType_tbl FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
 SET @query =
    'SELECT  LocName,Date, ' + @cols + '
     from  ( 
            select  l.LocName,v.Vtype, convert(date, dtime) as Date 
            from Transaction_tbl t 
            join VType_tbl v on t.vtid = v.vtid 
where dtime between ''' + @startdate + ''' and ''' + @enddate + ''' 
                and locid IN (SELECT l.Locid FROM dbo.Location_tbl l)
    ) d pivot ( count(Vtype) for Vtype in (' + @cols + ')  ) p '  
EXEC sys.sp_executesql @query
END  

在执行时我收到这样的错误:

无法绑定多部分标识符“l.LocName”。

我该如何解决这个问题?

4

2 回答 2

0

很简单。您的外部查询没有从lL 表中选择任何内容。您只在and locid IN (...)子查询中使用它。您不能在父查询中使用该子查询中的任何字段,除了一个l.locid字段,并且只能在IN (...)比较中使用。

于 2013-08-06T15:45:19.953 回答
0

要获取 locname,而不是使用子查询,请在连接中使用表名。这是示例:

ALTER PROCEDURE [dbo].[ParkingDeatailsReportnew] 
 @startdate NVARCHAR(100),
  @enddate NVARCHAR(100)AS BEGINDECLARE  @cols AS NVARCHAR(MAX) , @query AS NVARCHAR(MAX)
 SELECT @cols = STUFF((  SELECT DISTINCT ',' + QUOTENAME(Vtype)
  FROM dbo.VType_tbl FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
 SET @query =
    'SELECT  LocName,Date, ' + @cols + '
     from  ( 
            select  l.LocName,v.Vtype, convert(date, dtime) as Date 
            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 ''' + @startdate + ''' and ''' + @enddate + ''' 
                    ) d pivot ( count(Vtype) for Vtype in (' + @cols + ')  ) p '  
EXEC sys.sp_executesql @query
END  

在这里,我删除了子查询并将 Location_tbl 与 LocId 列上的 Transaction_tbl 连接起来。

于 2013-08-06T15:48:24.897 回答