I'm trying to make a stored procedure for a simple tanned system, my table is organized like this:
- Tanned
- id INT (11) - Auto Increment
- post INT (11) - foreign key (id - post)
- user INT (11) - foreign key (id - users)
- Users
- id INT (11) - Auto Increment
- name VARCHAR (15)
- Post
- id INT (11) - Auto Increment
- content VARCHAR (200)
My logic that I'm trying to apply:
- @valor: 1 = liked, 2 = did not like
- @post: post id
- @user: user id
1. If there is no value that matches the id of the user and the id id it creates one and appends the value to the type.
2. If it exists and the type is equal to the value sent it deletes.
3. If it exists and the type is different from the value, it updates.
CREATE DEFINER='root'@'localhost' PROCEDURE 'Teste'(
IN '@valor' INT,
IN '@post' INT,
IN '@user' INT
)
IF NOT EXISTS (SELECT * FROM curtida WHERE user = '@user' AND post = '@post')
BEGIN
INSERT INTO curtida (tipo, post, user) VALUES ('@valor', '@post', '@user');
END
ELSE
IF (SELECT tipo FROM curtida WHERE user = '@user' AND post = '@post') = '@valor'
BEGIN
DELETE FROM curtida WHERE user = '@user' AND post = '@post';
END
ELSE
BEGIN
UPDATE FROM curtida SET tipo = '@valor' WHERE user = '@user' AND post = '@post';
END