我有一个这样的存储过程:
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”。
如何解决此问题?
答案 0 :(得分:0)
很简单。您的外部查询未从l
L表中选择任何内容。您只在and locid IN (...)
子查询中使用它。您不能在父查询中使用该子查询中的任何字段,只能在l.locid
字段中使用EXCEPT,并且只能在IN (...)
比较中使用。
答案 1 :(得分: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
在这里,我删除了子查询,并在LocId列上使用Transaction_tbl加入了Location_tbl。