以下是我的存储过程的一部分,我使用它从我的数据库中提取数据。
查询
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
有时在数据库中,logtable(表在 logtable_1、logtable_2 .... 等变量中传递)
可能不存在,目前,当 perticuler 表丢失时,它会崩溃并抛出异常错误,因为如果没有日志表,a.time_start、a.time_end 就无法获得值。
但我想要的只是在值a.time_start, a.time_end
上分配NULL
而不抛出错误,
那么任何人都可以告诉我是否可以修改此代码,例如
BEGIN
if logtable exists
\\ the query
else
\\ the query
END
最佳答案
通过查询information_schema.tables
查找表是否存在。如果它返回的计数等于 1,那么您可以继续在表上执行查询。否则,请使用您的 Else
block 。
示例:
declare table_exists int default 0;
select count(1) into table_exists
from information_schema.tables
where table_schema='your_table_schema_name'
and table_name = 'your_table_name';
if table_exists then
-- do something
else
-- do something else
end if;
关于mysql - sql 查询中的 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30641516/