SQL 中的无限循环?

发布于 2024-11-06 06:34:11 字数 66 浏览 3 评论 0原文

有没有办法在SQL中实现无限循环?我正在思考一些就像在另一个中进行选择一样,递归地......(也许我在说愚蠢的事情)

There is some way to implement a infinite loop in SQL?? I was thinking on some like a select inside another one, recursively... (Maybe im talking foolishness)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

花海 2024-11-13 06:34:11

您可以使用 CTE 执行递归无限循环:

;with rec as
        (
        select  1 as n
        union all
        select  n + 1
        from    rec
        )
select  n
from    rec

默认情况下,SQL Server 将在 100 处停止;你可以让它永远循环:

option  (maxrecursion 0)

You can do a recursive infinite loop with a CTE:

;with rec as
        (
        select  1 as n
        union all
        select  n + 1
        from    rec
        )
select  n
from    rec

By default, SQL Server would stop at 100; you can make it loop forever with:

option  (maxrecursion 0)
阳光的暖冬 2024-11-13 06:34:11
WHILE 1=1
BEGIN
SELECT 'This will go forever'
END
WHILE 1=1
BEGIN
SELECT 'This will go forever'
END
水染的天色ゝ 2024-11-13 06:34:11

这应该在 oracle 中工作,

select * from (select level x from dual connect by  level >=0)

需要外部选择来避免客户端和数据库的某些组合发生的一些优化。

不完全确定 level >= 0 部分是否按预期工作,因为通常您只会将其与 level <= 50 之类的内容一起使用来获得固定数量的行。

This should work in oracle

select * from (select level x from dual connect by  level >=0)

the outer select is needed to avoid some optimizations which happen with some combinations of client and database.

Not completely sure if the level >= 0 part works as intended, since normally you would use this only with something like level <= 50 to get a fixed number of rows.

姐不稀罕 2024-11-13 06:34:11

我无法想象您为什么要这样做,但这将取决于您的实现(SQL Server、Oracle、MySQL...)支持的循环结构。

例如,在 SQL Server 中,您可以像使用任何命令式语言一样编写无限循环。大致:

DECLARE @x INT = 0
WHILE (@x = 0)
BEGIN
  PRINT @x
END

I can't imagine why you would want to do this, but it's going to depend on your implementation's (SQL Server, Oracle, MySQL...) supported loop constructs.

For example, in SQL Server, you would write an infinite loop the way you would in any imperative language. Roughly:

DECLARE @x INT = 0
WHILE (@x = 0)
BEGIN
  PRINT @x
END
删除→记忆 2024-11-13 06:34:11
DECLARE @number INT = 3

WHILE (@number = 3)
BEGIN
    PRINT @number
END
DECLARE @number INT = 3

WHILE (@number = 3)
BEGIN
    PRINT @number
END
别靠近我心 2024-11-13 06:34:11

您无法使用 SQL 等声明性语言创建无限循环,因为编译器不允许您这样做。您将收到错误消息和/或它无法运行。

您需要像 JNK 建议的那样,使用 SQL 编写顺序的内容。

You can't create an infinite loop with a declaritive language like SQL because the compiler's won't let you. You will get error messages and/or it just won't run.

You need to do something like what JNK suggested, using SQL to write something sequential.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文