Сценарий: В продолжение моего предыдущего вопроса ( Использование курсора в хранимой процедуре для зацикливания строк MySQL ) Я пытаюсь выполнить вложенный оператор подготовки, в который я ввожуdate для внешнего, и это вызывает внутренний, который получает данные из таблицы.
Код:
-- Create temporary table for the Output:
drop temporary table if exists `stats`;
create temporary table `stats`
(
col_name varchar(32) null,
num_nulls int null,
num_values int null
);
-- Procedure for the check:
drop procedure if exists `set_column_null_stats`;
delimiter $$
create procedure `set_column_null_stats`
(`p_col_name` varchar(128), `wanted_date` date)
begin
-- Set variables:
set @col_nme = `p_col_name`;
set @date1 = `wanted_date`;
prepare stmt from 'insert into `stats` (`col_name`) values (?);';
execute stmt using @col_nme;
deallocate prepare stmt;
-- count number of NULLS based on conditions:
set @sql_txt = concat(
'update `stats` s join(
select
count(1) as `nb`
from `btc`
where`btc`.`date` = ', @date1, ' and `btc`.`', @col_nme, '` is null)
t set `num_nulls` = t.`nb` where `col_name` = \'', @col_nme, '\';');
prepare stmt from @sql_txt;
execute stmt;
deallocate prepare stmt;
-- count number of not NULLS based on conditions:
set @sql_txt = concat(
'update `stats` s join(
select
count(1) as `nb`
from `btc`
where `btc`.`date` = ', @date1, ' and `btc`.`', @col_nme, '` is not null)
-- t set `num_values` = t.`nb` where `col_name` = \'', @col_nme, '\';');
set @sql_txt = concat('update `stats` s join (select count(1) as `nb` from `btc` where `', @col_nme, '` is not null) t set `num_values` = t.`nb` where `col_name` = \'', @col_nme, '\';');
prepare stmt from @sql_txt;
execute stmt;
deallocate prepare stmt;
end$$
delimiter ;
-- Procedure for looping through rows of `wanted_columns` table:
delimiter $$
drop procedure if exists `data_check_loop` $$
create procedure `data_check_loop`(`wanted_date` date)
begin
declare dateval date default null;
declare colval text default null;
-- boolean variable to indicate cursor is out of data
declare done tinyint default false;
-- declare a cursor to select the desired columns from the desired source table
declare cursor1
cursor for
select *
from `wanted_columns`;
-- catch exceptions
declare continue handler for not found set done = true;
set dateval = `wanted_date`;
-- open the cursor
open cursor1;
my_loop:
loop
fetch next from cursor1 into colval;
if done then
leave my_loop;
else
call `set_column_null_stats`(colval, dateval);
end if;
end loop;
close cursor1;
end $$
delimiter ;
-- Start the process with the wanted date:
call `data_check_loop`('2018-08-13');
select * from `stats`;
Проблема: Этот код работает без ошибок, но не дает никакого результата.Если я запускаю только первый подготовленный оператор, передавая переменные по одной, то все работает нормально.Я предполагаю, что проблема в моем втором утверждении.
Вопрос: Есть идеи о том, что я здесь не так делаю?
Obs: Второй код должен зацикливать строки таблицы (требуемые столбцы)) и подать их к первому утверждению, один за другим (вместе с датой, которая всегда должна быть одинаковой)
Obs2: Моя цель с этим запросом: из таблицы ссписок имен в виде строк («id1», «date1» ...) Я намерен прочитать каждую строку и использовать это значение в другой таблице, где имена («id1», «date1» ...) являются столбцами,и получить сумму для каждого из моих разыскиваемых столбцов значений NULL, а не NULL (также, учитывая другое ограничение ввода даты).Наконец, для каждой из моих исходных строк (таблица 1) я выведу новую строку с #NULL и # notNULL.
Пример.Таблица 1:
Col_names
Id1
Name1
Date1
Process
Time
Class
Пример.Таблица 2:
Id1 Name1 Date1 Process Time Class
aa test1 01/01 3 NULL A
NULL test2 01/02 4 NULL b
bb test3 NULL 3 NULL NULL
Пример.Выход:
Col_name #Null #notNull
Id1 1 2
Name1 0 3
Date1 1 2
Process 0 3
Time 3 0
Class 1 2