【问题标题】:SQL query and stored procedure not producing desired resultsSQL 查询和存储过程未产生预期结果
【发布时间】:2010-06-30 22:27:18
【问题描述】:

我有这个表和存储过程函数:

表:

CREATE TABLE _DMigNumbers(
    Number numeric(20,0) NOT NULL PRIMARY KEY
);
INSERT INTO _DMigNumbers VALUES(0)

存储过程函数:

CREATE FUNCTION read_and_increment()
RETURNS NUMERIC(20,0)
BEGIN
    DECLARE @number_just_read NUMERIC(20,0);

      SELECT number INTO @number_just_read
        FROM _DMigNumbers;

      UPDATE _DMigNumbers
         SET number = number + 1;
   RETURN @number_just_read;
End

我也创建了这个 Numbers 表

CREATE TABLE _Numbers (
    Number int NOT NULL PRIMARY KEY
);
INSERT INTO _Numbers VALUES(1)
INSERT INTO _Numbers VALUES(2)
INSERT INTO _Numbers VALUES(3)
INSERT INTO _Numbers VALUES(4)

现在:

当我这样做时:

select 
    f.Number
    ,read_and_increment()
from _Numbers f

我明白了:

数字-----值 1 0 2 0 3 0 4 0

我想要不同的值,例如 (0,1,2,3) - 我需要做什么才能实现这一目标?

我知道由于单次选择,我得到了相同的值,但不确定我需要做什么才能得到我现在所追求的......

我无法使用 IDENTITY 或自动增量,请参阅 my previous question for more details if interested...

谢谢,

巫毒

【问题讨论】:

  • 这似乎是巫毒编程。 afaik,这是我第一次在 SO 中看到这种查询(在执行选择时更新)问题
  • 根据另一篇文章接受的答案,您似乎缺少提交声明。这会在 Sybase 中自动发生吗?
  • 我无权访问 Sybase,因此无法运行该代码。但是在 SQL Server 中你不能创建这样的函数,你会得到错误:Invalid use of side-effecting or time-dependent operator in 'UPDATE' within a function.我不确定你在 Sybase 中是如何做到的。
  • 我用 MySQL 试了一下,第二列得到 NULL。
  • @g.d.d.c: 无论有没有提交语句,结果都是一样的。

标签: sql database stored-procedures sybase


【解决方案1】:

尝试将您的函数标记为NOT DETERMINISTIC,看看是否有帮助。默认情况下,所有函数都是确定性的,这意味着数据库服务器可以在某些情况下缓存结果。以这种方式标记它会强制服务器每次重新评估查询/函数。

CREATE FUNCTION read_and_increment()
RETURNS NUMERIC(20,0)
NOT DETERMINISTIC
BEGIN
    DECLARE @number_just_read NUMERIC(20,0);

      SELECT number INTO @number_just_read
        FROM _DMigNumbers;

      UPDATE _DMigNumbers
         SET number = number + 1;
   RETURN @number_just_read;
End

【讨论】:

  • 伙计,真是太棒了,它似乎奏效了。伙计,我希望我能给你一个+100。太棒了!
  • 只想说这对我有用,非常感谢 - 非常感谢您的帮助!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多