从sql表中递归选择数据

时间:2014-04-09 12:04:32

标签: sql sql-server tsql

我正在寻找SQL Query,我可以根据结果获取数据。例如,从用户表中我想选择前10条记录,其中用户ID在1到100之间。如果该范围内只有5条记录,我想将where子句id从1更改为200,如果仍然少于5记录我想再次从Id 1更改where子句到300.但我想这样做只到id为500或最多5递归。任何帮助都将非常感激。

DECLARE @retval int   
DECLARE @sSQL nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);

SELECT @sSQL = N'SELECT @retvalOUT = Count(CS.Id) FROM user where id between 1 and 100';

SET @ParmDefinition = N'@PostCode INT, @retvalOUT int OUTPUT';

EXEC sp_executesql @sSQL, @ParmDefinition,@PostCode, @retvalOUT=@retval OUTPUT;

IF ((SELECT @retval AS [Count]) > 10)
    BEGIN
           SET @sSQL = N'SELECT TOP 10 FROM user where id between 1 and 100';
       EXEC sp_executesql @mainSQL, @mainParmDefinition,@PostCode, @TOP_REC;
    END
ELSE
    BEGIN
           --SOMETHING HERE WHICH NEEDS TO BE RECURSIVE
    END

2 个答案:

答案 0 :(得分:1)

此查询将从您的表中返回10行,其中id介于(1,100)或(1,200)之间,依此类推

declare @lastid  int
declare @resultCount int
set @resultcount=0
set @lastid=0;
while (@resultcount<10)
begin
    set @lastid=@lastid+100;
    insert into #ResultTable 
          select top (10-@resultCount) * from user where id between (1,@lastid)
    where user.id not in (select id from #resultTable)
    set @resultcount=(select count(*) from #ResultTable);
end

如果您希望它只有5次递归,请将WHILE子句更改为:

while (@resultcount<10 AND @lastid<=500)

#ResultTable必须在执行此查询之前声明。

答案 1 :(得分:1)

问题中的描述有些令人困惑但是从评论中得到一些线索我认为你可以根据ID所在的范围对行进行排名,然后在选择前10行时按排名值排序,类似这样的:

SELECT TOP (10)
  ...  /* your columns */
FROM
  user
WHERE
  id BETWEEN 1 AND 500
ORDER BY
  (id - 1) / 100,  /* this will give you 0 for 1..100, 1 for 101..200 etc. */
  NEWID()          /* this is just a randomiser, remove it if you are happy
                      with IDs always starting from the beginning */
;