-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 に答える