-5

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

ALTER PROCEDURE [dbo].[ParkingDeatailsReportcheck]
    @locid INTEGER ,
    @startdate NVARCHAR(100) ,
    @enddate NVARCHAR(100)
AS 
    BEGIN
        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,Date, ' + @cols
            + '  from ( select l.LocName, v.Vtype, convert(date, dtime) as Date  from Transaction_tbl t  inner join VType_tbl v   on t.vtid = v.vtid
 join Location_tbl l on t.locid=l.Locid     where locid='
            + CAST(@locid AS VARCHAR(MAX)) + ' and dtime between '''
            + @startdate + ''' and ''' + @enddate + '''  ) d pivot   (      
              count(Vtype)
                for Vtype in (' + @cols + ')     ) p '
        EXECUTE(@query)
    END

执行此存储过程时出现如下错误:不明确的列名“locid”。我的预期输出是这样的:

 locationname   Date       Emaar Staff Lost Ticket Normal      VIP         VVIP
                ---------- ----------- ----------- ----------- ----------- -----------
 Fashion         2013-05-08      1           0           2           0           1
 Fashion         2013-05-25      0           0           1           1           0
 Fashion        2013-05-27       0           0           17          2           1   
4

2 回答 2

4

你有

join Location_tbl l on t.locid=l.Locid     where locid='

改成

join Location_tbl l on t.locid=l.Locid     where l.locid='

您需要表别名,它位于where之后的动态 SQL 中。

于 2013-08-07T11:32:14.847 回答
1

尝试改变:

where locid='

至:

where t.locid='

完整查询:

ALTER PROCEDURE [dbo].[ParkingDeatailsReportcheck] 

@locid INTEGER, 
@startdate NVARCHAR(100), 
@enddate NVARCHAR(100)

AS
BEGIN

    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,Date, ' + @cols + ' 
    from ( 
        select l.LocName, v.Vtype, convert(date, dtime) as Date 
        from Transaction_tbl t 
        inner join VType_tbl v on t.vtid = v.vtid 
        join Location_tbl l on t.locid=l.Locid 
        where t.locid=' + CAST(@locid AS VARCHAR(MAX)) + ' 
            and dtime between ''' + @startdate + ''' and ''' + @enddate + ''' 
    ) d 
    pivot (
        count(Vtype) for Vtype in (' + @cols + ') 
    ) p '

    EXECUTE (@query)
END
于 2013-08-07T11:33:41.650 回答