jeudi 4 juin 2015

if condition inside a sql query

following is a part of my stored proceedure im using it to extract data from my db.

query

BEGIN

SET @sqlstring = CONCAT("SELECT b.ID, c.name, c.accountID,, b.total_logs, a.time_start, a.time_end ,COUNT(a.id) AS number_of_users
FROM    ",logtable," a INNER JOIN users b on a.ID = b.ID INNER JOIN accounts c on b.accountID = c.accountID
GROUP BY ID;");
    PREPARE stmt FROM @sqlstring;
    EXECUTE stmt;

END

At times in the db, the logtable(table is passed in a variable like logtable_1, logtable_2 .... ) can be non existent, currently when the perticuler table is missing it crashes and throws an error because a.time_start, a.time_end cannot have values without the log table.

but what i want is just to assign NULL on values a.time_start, a.time_end without throwing an error,

So can any body tell is there a way i could modify this code like

BEGIN

if logtable exists
   \\ the query

else
   \\ the query

END

Aucun commentaire:

Enregistrer un commentaire