2013-08-28 20 views
13

Ho una procedura memorizzata MySQL dove trovo il valore massimo da una tabella.Come verificare se una variabile è NULL, quindi impostarla con una procedura memorizzata MySQL?

Se non c'è alcun valore, voglio impostare la variabile sulla data di ieri.

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; 

Il problema è che @last_run_time è sempre NULL.

Il seguente codice non viene eseguito per qualche motivo

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

Come posso impostare la variabile @last_run_time correttamente?

+1

Mi piace usare 'COALESCE' per la sostituzione di valori null. COALESCE (@last_run_time, Date_Sub (NOW(), INTERVAL 1 DAY)); http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce – actkatiemacias

+0

Grazie. Apparentemente il problema è che non sto usando le variabili correttamente. – Jaylen

risposta

24

@last_run_time è un 9.4. User-Defined Variables e last_run_time datetime uno 13.6.4.1. Local Variable DECLARE Syntax, sono variabili diverse.

Prova: SELECT last_run_time;

UPDATE

Esempio:

/* 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 ; 
+0

allora come posso rendere globali le prime 3 variabili? come ho bisogno di chiamarli più tardi nel mio codice? – Jaylen

+0

definirli prima di chiamare il proc memorizzato, in modo che abbiano un ambito esterno al proc. – Bohemian

+0

Devo definirli nella procedura perché devo solo usare con INIZIO .... FINE. Ma è necessario sapere qual è il modo corretto di usarli. – Jaylen

Problemi correlati