Jump to content

count records containing specific word from ALL tables.


87dave87

Recommended Posts

This might look prettier in PHP (or another language), but this should pass as a pure SQL solution:

 

DROP PROCEDURE IF EXISTS tally_os;
DELIMITER $$
CREATE PROCEDURE tally_os(IN var_os VARCHAR(20))
MAIN_BLOCK: BEGIN
DECLARE var_total INT UNSIGNED DEFAULT 0;
DECLARE var_table VARCHAR(255);
DECLARE var_no_more_tables BOOLEAN DEFAULT FALSE;
DECLARE cursor_tables CURSOR FOR SHOW TABLES;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET var_no_more_tables = TRUE;
OPEN cursor_tables;
TABLES: LOOP
	FETCH cursor_tables INTO var_table;
	IF var_no_more_tables THEN
		CLOSE cursor_tables;
		LEAVE TABLES;
	END IF;
	SET @sql = CONCAT('SELECT COUNT(*) FROM ', var_table, ' WHERE os = "', var_os, '" INTO @var_count');
	PREPARE stmt FROM @sql;
	EXECUTE stmt;
	SET var_total = var_total + @var_count;
	DEALLOCATE PREPARE stmt;
	SET @var_count = 0;
END LOOP TABLES;
SELECT var_total;
END MAIN_BLOCK;
$$
DELIMITER ;

 

Run with: CALL tally_os('windows');

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.