I have a lc_movimento
table with the fields:
id
, tipo
and valor
.
I need the valor
field to have the minus sign if is equal to tipo
every time I enter and update.
How can I do this?
I have a lc_movimento
table with the fields:
id
, tipo
and valor
.
I need the valor
field to have the minus sign if is equal to tipo
every time I enter and update.
How can I do this?
I need the
valor
field to have the minus sign if is equal totipo
every time I enter and update.
Pro development, I created the 0
table with the following structure :
+-------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+----------------+
| id | int(10) | NO | PRI | NULL | auto_increment |
| tipo | int(2) | YES | | NULL | |
| valor | float | YES | | NULL | |
+-------+---------+------+-----+---------+----------------+
Creating the trigger ) :
DELIMITER $$
CREATE TRIGGER gatilho_update
BEFORE UPDATE ON 'lc_movimento'
FOR EACH ROW
BEGIN
SET @tipo = NEW.tipo;
SET @valor = NEW.valor;
IF( @tipo = 0 ) THEN
SET NEW.valor = ( @valor * (-1) );
ELSE
SET NEW.valor = @valor;
END IF;
END$$
CREATE TRIGGER gatilho_insert
BEFORE INSERT ON 'lc_movimento'
FOR EACH ROW
BEGIN
SET @tipo = NEW.tipo;
SET @valor = NEW.valor;
IF( @tipo = 0 ) THEN
SET NEW.valor = ( @valor * (-1) );
ELSE
SET NEW.valor = @valor;
END IF;
END$$
DELIMITER ;
Inserting Data (Testing) :
INSERT INTO 'lc_movimento' ('tipo', 'valor') VALUES (1, 1234), (0, 17), (0, 83547), (1, 8637), (1, 1234), (0, 83142);
Checking data :
mysql> SELECT * FROM 'lc_movimento';
+----+------+--------+
| id | tipo | valor |
+----+------+--------+
| 1 | 1 | 1234 |
| 2 | 0 | -17 |
| 3 | 0 | -83547 |
| 4 | 1 | 8637 |
| 5 | 1 | 1234 |
| 6 | 0 | -83142 |
+----+------+--------+
6 rows in set (0.00 sec)
SELECT id, tipo,
CASE
WHEN tipo = 0 THEN valor*-1
WHEN tipo <> 0 THEN valor
END AS valor
FROM lc_movimento
case
does the test, and multiplication by -1 converts to negative.