1

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

ALTER procedure [dbo].[ParkingDeatailsReportnew] 
  @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 Date, ' + @cols + '
     from  ( select v.Vtype, convert(date, dtime) as Date 
     from Transaction_tbl t inner join VType_tbl v on t.vtid = v.vtid where dtime   between ''' + @startdate + ''' and ''' + @enddate + 
  '''and locid IN  ' + (select CAST(l.Locid  as varchar(max))  from Location_tbl l)
 + '  ) d pivot ( count(Vtype)     for Vtype in (' + @cols + ')  ) p '

   execute(@query)
end

执行此操作时出现如下错误:

子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。

我如何在子查询中传递超过 1 个值?

4

2 回答 2

2

我想说你的问题在这里:

(select CAST(l.Locid  as varchar(max))  from Location_tbl l)

您试图从返回的未知数量的行中形成一个字符串。

您可以只制作字符串的那一部分。

于 2013-08-04T13:06:55.960 回答
1

Try this one -

ALTER PROCEDURE [dbo].[ParkingDeatailsReportnew] 

    @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 dbo.VType_tbl
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

    SET @query =
    'SELECT Date, ' + @cols + '
     from  ( 
            select 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
于 2013-08-05T05:38:09.200 回答