【问题标题】:How to check if a variable is NULL, then set it with a MySQL stored procedure?如何检查变量是否为 NULL,然后使用 MySQL 存储过程设置它?
【发布时间】:2013-09-01 05:25:18
【问题描述】:

我有一个 MySQL 存储过程,可以从表中找到最大值。

如果没有值,我想将变量设置为昨天的日期。

DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time datetime DEFAULT NULL;
DECLARE current_run_time datetime DEFAULT NOW();

-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) 
FROM dynamo.runtimes WHERE procedure_name = @current_procedure_name);

-- if there is no last run time found then use yesterday as starting point
IF(@last_run_time IS NULL) THEN
    SET last_run_time := DATE_SUB( NOW(), INTERVAL 1 DAY);
END IF;

SELECT @last_run_time;

问题是@last_run_time 始终为NULL。

以下代码由于某种原因没有被执行

IF(last_run_time IS NULL) THEN
    SET last_run_time := DATE_SUB( NOW(), INTERVAL 1 DAY);
END IF;

如何正确设置变量@last_run_time

【问题讨论】:

  • 我喜欢使用COALESCE 来替换空值。 COALESCE(@last_run_time, Date_Sub(NOW(), INTERVAL 1 DAY)); dev.mysql.com/doc/refman/5.0/en/…
  • 谢谢。显然问题是我没有正确使用变量。

标签: mysql stored-procedures


【解决方案1】:

@last_run_time 是一个9.4. User-Defined Variableslast_run_time datetime 一个13.6.4.1. Local Variable DECLARE Syntax,是不同的变量。

试试:SELECT last_run_time;

更新

例子:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

【讨论】:

  • 那么我怎样才能使前 3 个变量成为全局变量?因为我需要稍后在我的代码中调用它们?
  • 在调用存储过程之前定义它们,因此它们在过程之外有一个范围。
  • 我需要在过程中定义它们,因为我只需要在 BEGIN....END 中使用 with。但需要知道正确的使用方法是什么。
  • 我不知道您正在尝试做什么,并且当您说稍后在代码中调用它们时不明白您的意思。用户定义的变量是特定于会话的,我们可以说是会话的“全局”。
  • 我的意思是,我想在 select 语句的顶部定义一个变量。如果在数据库中找到注释,则将该变量设为昨天。稍后我想将这 3 个变量的值插入到另一个表中。那么如何正确设置变量?谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多