我有一个应该执行示例代码的存储过程:
IF EXISTS (
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME IN ('TB1', 'TB2', 'TB3')
AND COLUMN_NAME = 'COL'
AND table_schema = 'TestDB'
GROUP BY TABLE_NAME
HAVING count (TABLE_NAME) = 3
)
THEN
/*Used for debugging*/
SELECT 'Tables EXIST' INTO msg;
ELSE
/*Used for debugging*/
SELECT 'NON-EXISTENT TABLES !' INTO msg;
END IF

基本上,我希望上面的代码段选择所有具有名为' COL'的列的指定表。我只想使用information_schema来做这件事,没有别的。
检查后,测试语句(IF EXISTS)始终返回false。也就是说,即使我的三个测试表(TB1,TB2和TB3)具有COL字段,ELSE语句也始终执行。我犯了什么罪?
答案 0 :(得分:0)
与此平行的东西应该有效
select distinct
table_name
from information_schema.columns
where column_name = 'CHARACTER_SET_NAME'
and table_name in ('CHARACTER_SETS', 'COLLATIONS', 'COLUMNS', 'TRIGGERS', 'FOO', 'BAR')
;
你有这个
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME IN ('TB1', 'TB2', 'TB3')
AND COLUMN_NAME = 'COL'
AND table_schema = 'TestDB'
GROUP BY TABLE_NAME
HAVING count (TABLE_NAME) = 3
)
即。这样:
select distinct
table_name
from information.schema.columns
where table_name in ('TB1', 'TB2', 'TB3')
and column_name = 'COL'
and table_schema = 'TestDB'
如果你想确保所有三个表都存在并且有一个' COL'列写一个条件来检查这个值是否为3
select count(*) from (
select distinct
table_name
from information.schema.columns
where table_name in ('TB1', 'TB2', 'TB3')
and column_name = 'COL'
and table_schema = 'TestDB'
) tbls
;
答案 1 :(得分:0)
你可以这样做:
功能:
CREATE DEFINER=`root`@`localhost` FUNCTION `new_function`() RETURNS varchar(64) CHARSET utf8
BEGIN
declare cnt int;
declare msg varchar(64);
select count(*) from (
select distinct
table_name
from information_schema.columns
where table_name in ('TB1', 'TB2', 'TB3')
and column_name = 'COL'
and table_schema = 'TestDB'
) tbls into cnt;
if cnt = 3 then
select 'tables exist' into msg;
else
select 'tables do not exists' into msg;
end if;
RETURN msg;
END
然后运行:
create schema TestDB;
use TestDB;
create table TB1(
COL int
);
create table TB2(
COL int
);
create table TB3(
COL int
);
select new_function();
这将返回: 表存在