执行存储过程时获取不明确的列名称错误

时间:2013-08-07 11:28:11

标签: sql-server

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

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   

2 个答案:

答案 0 :(得分:4)

你有

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

更改为

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

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

答案 1 :(得分: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