DELIMITER $$
use vte_dev$$

DROP PROCEDURE IF EXISTS `storeParamValue`$$
CREATE PROCEDURE `storeParamValue`(
	name varchar(255),
		val varchar(255))
MODIFIES SQL DATA
BEGIN
	declare inputId, inputValId int;
	
	select i.id, iv.id into inputId, inputValId
	from input_val iv
	inner join `input` i on i.id=iv.input_id
	where i.name=name
	and iv.`value`=val;
	
	if inputId is not null and inputValId is not null then
		if exists(
			select * from param_val pv
			inner join input_val iv on iv.id=pv.inputval_id
			where iv.input_id = inputId)
		then
			delete from param_val
			where inputval_id in
				(select pv.inputval_id
				from param_val pv
				inner join input_val iv on iv.id=pv.inputval_id
			where iv.input_id = inputId);
		end if;
	
		insert into param_val(inputval_id) values(inputValId);
	end if;
END$$
