SQL Server:LIMIT不处理复杂查询

时间:2013-09-17 02:09:34

标签: sql sql-server

我目前正在处理一个相当长而复杂的SQL查询。

我想要做的只是添加LIMIT 10 ...但每次我结束查询结束时我都会遇到错误。

任何帮助都会令人惊叹,查询如下:

sqlQuery = "
  select      DATENAME(Month,i.Datecreated) + ' ' + 
              DATENAME(day,i.Datecreated) + ' ' + 
              DATENAME(year,i.Datecreated) AS USDateCreated,
              i.imageId,
              GalleryName,Fullpath,MediumPath,ThumbPath,ViewCounter,
              i.DateCreated,ItemNumber,Gender,Minutes,
              right(convert(varchar(3), 100 + Seconds),2) as Seconds,
              FramesPerSecond,WeekNumber,Filename,
              (round(cast(Size as Decimal(16,2))/1024,2)) as Size,
              FlvFilename,FlvSize,NumberOfMovies,
              Free,Comment,
              (case when sum(rating)/count(i.imageId) is null then 0 else sum(rating)/count(i.imageId) end) as ratingResult, 
              dbo.getTagNames(i.imageid) as tagsname,'' as yourTagNames,
              dbo.getTagNames(i.imageid) as memberTagNames,max(weekNumber)-1 as lastWeek 

  from        images as i 

  left join   Imagerating as ir on i.imageId = ir.imageId

  left join   tag as t on i.imageId = t.imageId where 1=1 

  and         galleryName = 'pictures' 

  and         weekNumber = '4' 

  group by    i.imageId,GalleryName,Fullpath,MediumPath,ThumbPath,
              ViewCounter,i.DateCreated,ItemNumber,Gender,Minutes,Seconds,
              FramesPerSecond,WeekNumber,Filename,Size,FlvFilename,FlvSize,
              NumberOfMovies,Free,Comment 

  order by    filename
"

3 个答案:

答案 0 :(得分:6)

T-SQL不支持LIMIT。相反,请在SELECT中使用TOP

SELECT TOP 100 -- Rather than LIMIT 100 at the bottom
    Field1, Field2 -- etc.
FROM YourTable
GROUP BY Field1
ORDER BY Field2

如果您使用的是SQL Server 2012或更高版本,则可以使用OFFSET and FETCH [FIRST|NEXT]获取LIMIT浏览结果集的功能。

答案 1 :(得分:1)

在TSQL中,使用的函数是TOP,而不是LIMIT:

SELECT TOP 10 * FROM Table

答案 2 :(得分:1)

LIMIT在Sql Server中不起作用。它是标准SQL的MySql专有扩展。在Sql Server中,您可以使用简单的TOP n作为第一页,但如果您尝试进行分页,那么这不是一个好的选择。

幸运的是,SQL标准的更新版本指定了可用于分页的语法,如果您很幸运能够使用Sql Server 2012或更高版本,则可以使用它。它被称为OFFSET/FETCH,它看起来像这样:

SELECT <columns> FROM <table> ORDER BY <order> OFFSET 30 ROWS FETCH NEXT 15 ROWS ONLY;

如果页面大小为15,则会获取 3rd 页面。请注意,ORDER BY子句是必需的。否则,偏移没有意义。这是标准sql 。 Sql Server不仅支持它,而且Oracle,PostGre和其他一些产品也支持它,并且您可以随着时间的推移导出更多。

相关问题