SQL Server 中的查询不稳定

发布于 2024-10-20 16:02:49 字数 959 浏览 1 评论 0原文

我使用的是 SQL Server 2008-R2 Express 版。

我编写了如下所示的查询来生成从 1 到 @n 的数字序列。在测试它时(纯粹在查询窗口中),我发现如果我显着更改 @n 的值,我会得到不正确的结果。重新执行会产生相同的错误。但是,如果我打开一个新的查询窗口,结果是完美的。

看看算法,我不明白为什么我应该得到不稳定的结果(甚至查询可以针对固定输入产生不同的结果)。

DECLARE @n INT;

SET @n = 65536;

DECLARE @t TABLE (n INT NOT NULL PRIMARY KEY);

IF @n > 0 BEGIN
    DECLARE @r INT, @i INT, @l INT;

    SET @r = FLOOR(1.442695040888964 * LOG(@n));
    SET @i = 1;
    SET @l = 0;

    INSERT INTO @t (n) VALUES (1);

    WHILE @l < @r BEGIN
        INSERT INTO @t (n) SELECT n + @i FROM @t;

        SET @i = @i * 2;
        SET @l = @l + 1;
    END;

    INSERT INTO @t (n) SELECT TOP (@n - @i) n + @i FROM @t;
END;

--SELECT COUNT(1) FROM @t;

select * from @t

编辑

将 65536 更改为 5000,执行,更改回 65536,然后向下滚动到第 169,770 行。我得到行 169770 = 40000。在新窗口中,它运行正确。

EDIT2

除了随机获得正确/不正确的结果之外,似乎还有其他问题。我现在得到的某些数字始终不正确,例如 655360。

I am using SQL Server 2008-R2 Express Edition.

I wrote the query shown below to generate number sequences from 1 to @n. In testing it (purely in a query window), I found that if I significantly change the value of @n, I get incorrect results. Re-execution yields the same errors. However, if I open a new query window, the results are perfect.

Looking at the algorithm, it makes no sense to me as to why I should be getting unstable results (or even that a query can produce varying results against a fixed input).

DECLARE @n INT;

SET @n = 65536;

DECLARE @t TABLE (n INT NOT NULL PRIMARY KEY);

IF @n > 0 BEGIN
    DECLARE @r INT, @i INT, @l INT;

    SET @r = FLOOR(1.442695040888964 * LOG(@n));
    SET @i = 1;
    SET @l = 0;

    INSERT INTO @t (n) VALUES (1);

    WHILE @l < @r BEGIN
        INSERT INTO @t (n) SELECT n + @i FROM @t;

        SET @i = @i * 2;
        SET @l = @l + 1;
    END;

    INSERT INTO @t (n) SELECT TOP (@n - @i) n + @i FROM @t;
END;

--SELECT COUNT(1) FROM @t;

select * from @t

EDIT

Change the 65536 to 5000, execute, change back to 65536, and scroll down to say row 169,770. I get row 169770 = 40000. In a new window, it runs correctly.

EDIT2

Besides getting randomly correct/incorrect results, it appears something else is wrong. I now am getting consistently incorrect results for some numbers such as 655360.

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

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

发布评论

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

评论(1

贪恋 2024-10-27 16:02:49

将 ORDER BY 添加到最后一个语句。

任何表格中都没有自然或默认顺序

编辑:

我将其归因于浮点数的使用

我在一小时前发布了如何制作统计表:最大递归已用尽

Add an ORDER BY to the last statement.

There is no natural or default order in any table

Edit:

I attribute it the use of floating point numbers

I posted how to do a tally table an hour ago: Maximum recursion has been exhausted

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