1

我有一个在 SQL Server Management Studio 中运行良好的 SQL 查询,但是当我将其复制并粘贴到 jasperreports 的 iReport 中以生成报告时,它给了我一个 SQL Server 异常并说该语句没有返回结果集。这让我很困惑。

查询是:

declare @index int = 1

declare @t Table(ID INT, DI INT, INDBOOK1 INT, INDBOOK2 INT, delta INT)

while(@index < 18)
begin
   INSERT INTO @t
      select distinct top 18
         col1.ID,
         col1.DI,
         col1.INDBOOK as INDBOOK1,
         col2.INDBOOK as INDBOOK2,
         col2.INDBOOK - col1.INDBOOK 
      FROM  
          table as col1
      inner join 
          table as col2 on col2.ID = @index 
                        and col2.DI = col1.DI+1 
      where 
          col1.ID = @index

   set @index = @index + 1
end

select ID, DI, INDBOOK1, INDBOOK2, delta FROM @t

有谁知道为什么这给了我没有返回结果集的异常?

任何帮助表示赞赏。

4

1 回答 1

0

没有样本数据等很难说,但我认为这应该接近你需要的,在一个没有显式循环的语句中:

;WITH x([index]) AS 
(
  SELECT TOP (18) ROW_NUMBER() OVER (ORDER BY number)
  FROM master..spt_values ORDER BY number
),
y AS 
(
  SELECT [index] = ROW_NUMBER() OVER (PARTITION BY col1.ID ORDER BY col1.ID),
         col1.ID, col1.DI, col1.INDBOOK as INDBOOK1, col2.INDBOOK as INDBOOK2,
         col2.INDBOOK - col1.INDBOOK as delta
      FROM dbo.table as col1
      INNER JOIN dbo.table as col2 
        ON col2.ID = col1.ID
        AND col2.DI = col1.DI+1 
)
SELECT y.ID, y.DI, y.INDBOOK1, y.INDBOOK2, y.delta
FROM x INNER JOIN y
ON x.[index] = y.[index]
WHERE y.[index] <= 18;
于 2013-10-14T15:11:59.637 回答