4 个解决方案
#1
表要先排序的哈,不然没有意义,,假设按id列排序的
CREATEPROCEDURE dbo.stp_Test
(
@N INT = 0,
@TableName nvarchar(max)
)
AS
DECLARE @sql nvarchar(max)
BEGIN
SET @sql = 'SELECT TOP('+CAST(@N+1 AS nvarchar(10))+') * FROM '+ @TableName+
' WHERE id not in (SELECT TOP('+CAST(@N-1 AS nvarchar(10))+') id FROM '+ @TableName+' order by id)
ORDER BY id'
print @sql
EXEC SP_EXECUTESQL @sql
END
CREATEPROCEDURE dbo.stp_Test
(
@N INT = 0,
@TableName nvarchar(max)
)
AS
DECLARE @sql nvarchar(max)
BEGIN
SET @sql = 'SELECT TOP('+CAST(@N+1 AS nvarchar(10))+') * FROM '+ @TableName+
' WHERE id not in (SELECT TOP('+CAST(@N-1 AS nvarchar(10))+') id FROM '+ @TableName+' order by id)
ORDER BY id'
print @sql
EXEC SP_EXECUTESQL @sql
END
#2
sorry 刚才脑子坏掉了,理解错了
CREATE PROCEDURE dbo.stp_Test
(
@N INT = 0,
@TableName nvarchar(max)
)
AS
DECLARE @sql nvarchar(max)
BEGIN
SET @sql = 'SELECT TOP 2 * FROM (SELECT TOP (' +CAST(@N+1 AS nvarchar(10)) + ') * FROM '+@TableName+' ORDER BY cuan) AS tmp ORDER BY cuan DESC'
print @sql
EXEC SP_EXECUTESQL @sql
END
CREATE PROCEDURE dbo.stp_Test
(
@N INT = 0,
@TableName nvarchar(max)
)
AS
DECLARE @sql nvarchar(max)
BEGIN
SET @sql = 'SELECT TOP 2 * FROM (SELECT TOP (' +CAST(@N+1 AS nvarchar(10)) + ') * FROM '+@TableName+' ORDER BY cuan) AS tmp ORDER BY cuan DESC'
print @sql
EXEC SP_EXECUTESQL @sql
END
#3
--SQL 2012
select * from 某表 order by 某表ID offset N rows fetch next I rows only
#4
mssql2000 top 嵌套
2005~2008 可以row_number排序取范围
2012 以上可以offset
2005~2008 可以row_number排序取范围
2012 以上可以offset
#1
表要先排序的哈,不然没有意义,,假设按id列排序的
CREATEPROCEDURE dbo.stp_Test
(
@N INT = 0,
@TableName nvarchar(max)
)
AS
DECLARE @sql nvarchar(max)
BEGIN
SET @sql = 'SELECT TOP('+CAST(@N+1 AS nvarchar(10))+') * FROM '+ @TableName+
' WHERE id not in (SELECT TOP('+CAST(@N-1 AS nvarchar(10))+') id FROM '+ @TableName+' order by id)
ORDER BY id'
print @sql
EXEC SP_EXECUTESQL @sql
END
CREATEPROCEDURE dbo.stp_Test
(
@N INT = 0,
@TableName nvarchar(max)
)
AS
DECLARE @sql nvarchar(max)
BEGIN
SET @sql = 'SELECT TOP('+CAST(@N+1 AS nvarchar(10))+') * FROM '+ @TableName+
' WHERE id not in (SELECT TOP('+CAST(@N-1 AS nvarchar(10))+') id FROM '+ @TableName+' order by id)
ORDER BY id'
print @sql
EXEC SP_EXECUTESQL @sql
END
#2
sorry 刚才脑子坏掉了,理解错了
CREATE PROCEDURE dbo.stp_Test
(
@N INT = 0,
@TableName nvarchar(max)
)
AS
DECLARE @sql nvarchar(max)
BEGIN
SET @sql = 'SELECT TOP 2 * FROM (SELECT TOP (' +CAST(@N+1 AS nvarchar(10)) + ') * FROM '+@TableName+' ORDER BY cuan) AS tmp ORDER BY cuan DESC'
print @sql
EXEC SP_EXECUTESQL @sql
END
CREATE PROCEDURE dbo.stp_Test
(
@N INT = 0,
@TableName nvarchar(max)
)
AS
DECLARE @sql nvarchar(max)
BEGIN
SET @sql = 'SELECT TOP 2 * FROM (SELECT TOP (' +CAST(@N+1 AS nvarchar(10)) + ') * FROM '+@TableName+' ORDER BY cuan) AS tmp ORDER BY cuan DESC'
print @sql
EXEC SP_EXECUTESQL @sql
END
#3
--SQL 2012
select * from 某表 order by 某表ID offset N rows fetch next I rows only
#4
mssql2000 top 嵌套
2005~2008 可以row_number排序取范围
2012 以上可以offset
2005~2008 可以row_number排序取范围
2012 以上可以offset