You can use an IF statement in a MySQL stored procedure to control the actions that are taken.
The syntax is as follows:
IF condition THEN ... do something ... END IF;
The condition in your IF statements can be similar to the conditions in CASE statements. For additional information, check out MySQL’s web site.
You can also retrieve the auto increment ID after you perform an insert. Just use the following query:
SELECT LAST_INSERT_ID() into artist_id;
For this project, create a new procedure called AddAlbum. It will take at least two parameters – NameOfArtist and AlbumName (just like in the last project).
Your procedure needs to check the Artists table to see if an NameOfArtist exists. If it does not exist, you’ll need to add a new row. Here are the steps:
- Use the COUNT aggregate on Artists to see how many rows exist for NameOfArtist. Store the count in a variable called artist_count.
- If artist_count is zero, insert a new row into Artists.
— Select the LAST_INSERT_ID() into a variable.
- If artist_count is one, lookup the ArtistID and store it in a variable.
- Insert a new row into the Albums table.
code:
CREATE PROCEDURE AddAlbum(
NameOfArtist varchar(50),
AlbumName varchar(50)
);
BEGIN
DECLARE artist_count INT;
DECLARE artist_id INT;
SELECT COUNT(ArtistName) INTO artist_count FROM Artists
WHERE ArtistName = NameOfArtist;
IF artist_count = 0
THEN SELECT LAST_INSERT_ID(NameOfArtist) INTO artist_id
AND INSERT INTO Artists (ArtistName)
VALUES (NameOfArtist)
END IF;
IF artist_count = 1
THEN SELECT ArtistID INTO artist_id
FROM Artists
WHERE ArtistName = NameOfArtist
END IF;
INSERT INTO Albums (ArtistID, Title)
VALUES (artist_id, AlbumName);
END;
//
This is what I’m trying, for the class I’m currently taking. Honestly, I’m not understanding how to write the code too well. I understand exactly what needs to be done, my brain for some reason is just not processing how to write the code correctly for some reason.
I’m fairly certain that I have a lot of errors, I’ve been working on it quiet some time, and just can’t seem to get it. Been re-thinking this database admin course I’m taking. But, I’m not going to give up.
Is there anyone on who can assist me with this?
If you need to follow the exact steps, this would be your code: