1

I am having an issue creating a trigger in my database. The idea is that, when a song is removed from a playlist, the corresponding row is deleted from the table playlistcancion. The idea of the trigger is that it removes the time of the deleted song from the total time of the playlist.

view name: pycs (shows songs of corresponding playlists)
column name | SongID | playlistID | Playlist | songName | Duration
data type   | INT    | INT        | varchar  | varchar  | TIME 

table name: playlistcancion (keeps track of which songs are in which playlists)
column name | songID | playlistID 
data type   | INT    | INT   

table name: playlists (playlist data and creators userID)
column name | playlistID| userID  | Followers  | Title  | TotalDuration
data type   | INT       | INT     | INT        | varchar| TIME 

Here is my trigger query:

CREATE TRIGGER remove_time
AFTER DELETE ON playlistcancion
FOR EACH ROW 
    DECLARE dur TIME;
    SELECT Duration INTO dur FROM pycs WHERE playlistID = OLD.playlistID AND songID = OLD.songID;
    UPDATE playlists SET TotalDuration = SEC_TO_TIME(TIME_TO_SEC(TotalDuration) - TIME_TO_SEC(dur))
    WHERE playlistID = OLD.playlistID;

The error i am getting is: MySQL said: #1064 - There's something wrong with your syntax near 'DECLARE dur TIME; SELECT Duration INTO dur FROM pycs WHERE playlisID = OLD.pla' in line 1 I am using phpMyAdmin to create the trigger. Thanks in advance.

2 Answers 2

1

Adding BEGIN and END resolved that error you are getting.

CREATE TRIGGER remove_time
AFTER DELETE ON playlistcancion
FOR EACH ROW BEGIN
    DECLARE dur TIME;
    SELECT Duration INTO dur FROM pycs WHERE playlistID = OLD.playlistID AND songID = OLD.songID;
    UPDATE playlists SET TotalDuration = SEC_TO_TIME(TIME_TO_SEC(TotalDuration) - TIME_TO_SEC(dur))
    WHERE playlistID = OLD.playlistID;
    END;

If you face more issue better post with insert script of all the tables involved in the triggers.

Sign up to request clarification or add additional context in comments.

Comments

1

Combine your trigger into single-statement form:

CREATE TRIGGER remove_time
AFTER DELETE 
ON playlistcancion
FOR EACH ROW 
UPDATE playlists 
SET TotalDuration = SEC_TO_TIME(   TIME_TO_SEC(TotalDuration) 
                                 - TIME_TO_SEC(SELECT Duration 
                                               FROM pycs 
                                               WHERE playlistID = OLD.playlistID 
                                                 AND songID = OLD.songID))
WHERE playlistID = OLD.playlistID;

Now it does not need in intermediate variable, BEGIN-END block and DELIMITER reassign.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.