【问题标题】:selecting data recursively from sql table从sql表中递归选择数据
【发布时间】:2014-04-11 15:51:53
【问题描述】:

我正在寻找可以根据结果获取数据的 SQL 查询。例如,从表用户中,我想选择用户 id 介于 1 到 100 之间的前 10 条记录。如果该范围内只有 5 条记录,我想将 where 子句 id 从 1 更改为 200,如果仍然少于 5记录我想再次将 where 子句从 Id 1 更改为 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

【问题讨论】:

  • 您在问题中使用 5,但在代码中使用 10。我不确定这与仅从 id
  • 如果超过 10 我想选择前 10 条记录,但如果它小于 10 则我需要更改 id 并在结果超过 10 时再次选择前 10
  • 为什么在迭代时需要递归?
  • 迭代示例也很棒..
  • 我同意 paqogomez。似乎您想要的只需select top 10 ... where id < 500 即可完成。如果不是这种情况,那么也许您可以在此处对您要执行的操作给出更高级别的解释。

标签: sql sql-server tsql


【解决方案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 必须在执行此查询之前声明。

【讨论】:

    【解决方案2】:

    问题中的描述有些令人困惑,但从 cmets 获得一些线索,我认为您可以根据 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 */
    ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多