有没有办法在通配符选择中的所有列上测试null?

时间:2013-07-01 17:07:29

标签: mysql

伪:

select * from foo where [every column is not null]

有没有办法在不指定实际列名的情况下执行此操作?

1 个答案:

答案 0 :(得分:6)

我能想到的一个可能的解决方案是使用dynamic-SQL

SELECT GROUP_CONCAT(column_name SEPARATOR ' IS NOT NULL AND ')
   INTO @sql
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_schema = SCHEMA()
   AND table_name = 'foo'
 GROUP BY table_name;

SET @sql = CONCAT('SELECT * FROM foo WHERE ', @sql, ' IS NOT NULL');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

这是 SQLFiddle 演示


显然它可以包装到带有表名参数的存储过程中

DELIMITER $$
CREATE PROCEDURE sp_select_all_not_null(IN tbl_name VARCHAR(64))
BEGIN
  SELECT GROUP_CONCAT(column_name SEPARATOR ' IS NOT NULL AND ')
     INTO @sql
    FROM INFORMATION_SCHEMA.COLUMNS
   WHERE table_schema = SCHEMA()
     AND table_name = tbl_name
   GROUP BY table_name;

  SET @sql = CONCAT('SELECT * FROM ', tbl_name, ' WHERE ', @sql, ' IS NOT NULL');

  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END
DELIMITER ;

然后使用它

CALL sp_select_all_not_null('foo');

以下是 SQLFiddle 演示