Issue with stored procedure and COUNT IF statement - mysql

So I need to make a stored procedure called AddComment, that will add a comment to my Comments table , then add an entry into the Commenters table if that commenters name does not exist.
DELIMITER //
CREATE PROCEDURE AddComment(Name VARCHAR(60), Title VARCHAR(60), Comments VARCHAR(60))
BEGIN
INSERT INTO Comments(Name, Title, Comments)
VALUES (Name, Title, Comments);
DECLARE name_count INT;
SELECT COUNT(Name) INTO name_count
FROM Commenters
WHERE Name = Name;
IF name_count = 0
THEN INSERT INTO Commenters(Name)
VAlUES(Name);
ELSEIF name_count = 1
THEN INSERT IGNORE Commenters(Name)
VALUES(Name);
END IF;
END;
//
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version fo
r the right syntax to use near 'DECLARE name_count INT;
SELECT COUNT(Name) INTO name_count
FROM Commenters
^ Is the error I'm getting. I keep tweaking my code trying to figure it out, but nothing is working.

You need a cursor to use syntax like that, but you can use SET:
SET name_count = (SELECT COUNT(*) ...);
Or better yet, since you don't actually use the value, eliminate the variable entirely:
IF NOT EXISTS (SELECT * FROM ...) THEN

Related

MySQL creating procedure getting error I cannot figure out why

I want to create a procedure for a MySql database but I get this error below and after 2h of research I still cannot figure out why.
The code is the following :
delimiter //
create procedure mitarbeiter_projekt (proj_name varchar(20), mitarb_name varchar(20))
begin
declare pruef_id int;
declare new_id int;
declare mitarb_id int;
select count(id) from t_proj where name = proj_name into pruef_id;
select id from t_ma_dt where name = mitarb_name into mitarb_id;
if pruef_id = 0 then
select max(id) + 1 from t_proj into new_id;
insert into t_proj (id, name) values (new_id, proj_name);
insert into t_ma_proj (ma_id, proj_id )values (mitarb_id, new_id);
else
select id from t_proj where name = proj_name into new_id;
insert into t_ma_proj (ma_id, proj_id) values (mitarb_id, new_id);
end //
"ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near '' at line 15"
all of the above tables I used exist in my database.
Thankful for any help!

SQL variable in IF exists

I can't figure out the correct way to assign query output into a variable that i could later use in an INSERT clause.
The error I get is
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET #lennuid = (select lend_id from lend where sihtpunkt=in_kuhu AND kuupaev=in_' at line 8
I've tried looking at every guide on variables in SQL but none of them could help me solve this.
Iam using the below code:
CREATE PROCEDURE proov(
in_kuhu varchar(50), in_nimi1 varchar(50), in_nimi2 varchar(50), in_adre varchar(50), in_telo varchar(20), in_email varchar(100), in_date date)
BEGIN
DECLARE viga INTEGER DEFAULT 0 ;
DECLARE lennuid INT;
START TRANSACTION;
IF exists (
SET #lennuid = (select lend_id from lend where sihtpunkt=in_kuhu AND kuupaev=in_date)) THEN
INSERT INTO broneering
(lend_id, bron_aeg, eesnim, perenimi, aadress, telefon, email)
VALUES
(lennuid, NOW(), in_nimi1, in_nimi2, in_adre, in_telo, in_email);
ELSE
set viga=1;
SELECT 'Muudatus ebaonnestus ',viga;
END IF;
IF viga=0 then
COMMIT;
select 'korras';
ELSE
select 'tagasi';
ROLLBACK;
END IF;
THEN causing the issue.
IF exists (
SET #lennuid = (select lend_id from lend where sihtpunkt=in_kuhu AND kuupaev=in_date))
BEGIN -- Instead of THEN use BEGIN , END
INSERT INTO broneering
(lend_id, bron_aeg, eesnim, perenimi, aadress, telefon, email)
VALUES
(lennuid, NOW(), in_nimi1, in_nimi2, in_adre, in_telo, in_email);
END
ELSE
BEGIN
set viga=1;
SELECT 'Muudatus ebaonnestus ',viga;
END
END IF;
You might want to use SELECT INTO:
select lend_id into #lennuid
from lend
where sihtpunkt=in_kuhu AND kuupaev=in_date;
Alternatively:
select #lennuid := lend_id
from lend
where sihtpunkt=in_kuhu AND kuupaev=in_date;
Either way works the same, then you can use that variable however you like...
In your particular example, though, the problem is actually how your exists is being used along with the set. To fix this, use the following:
IF exists (select lend_id from lend where sihtpunkt=in_kuhu AND kuupaev=in_date) THEN ...
What the problem here is, is you were setting a variable with SET inside of the EXISTS check.
Or you could do your select first as a COUNT into a numeric variable:
DECLARE cnt INTEGER;
select Count(lend_id) into #cnt
from lend
where sihtpunkt=in_kuhu
and kuupaev=in_date;
IF #cnt > 0 THEN
END IF;

SQL Trigger solve

CREATE TRIGGER Print
Before UPDATE ON employ
FOR EACH ROW
WHEN (NEW.Employe_ID>0)
DECLARE
salary int;
BEGIN
salary:= :NEW.salary-:OLD.salary;
dbms_output.put('Old salary:'||:OLD.salary);
dbms_output.put('New salary:'||:NEW.salary);
dbms_output.put_line('Difference'||salary);
END;
/
Shows
error 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHEN (NEW.Employe_ID>0)
DECLARE
salary int' at line 4
I have a table name employe which has 4 columns Employe_ID, E_name,
Department_ID,
salary
What is the problem with this sql and how can I solve it?
I don't get why you added the condition on employee_id > 0, but in case you actually need it
delimiter //
CREATE OR REPLACE TRIGGER print BEFORE UPDATE ON employee
FOR EACH ROW
IF ( NEW.employe_id > 0 ) THEN
SELECT NEW.salary - OLD.salary INTO #delta;
END IF;
//
delimiter ;
Insert and update your data, then read #delta
insert into employee select 1,'Me',1,2400;
update employee set salary = 2800 where id = 1;
Select #delta;
I don't think it's possible to automatically output #delta to the screen as it would be on Oracle using dbms_output.put_line().

stored procedure with count(*) and if statement

I have a problem with this sql code.
I have a table friends with three columns user1, user2, pending.
user1 and user2 are primary keys of datatype int.
The phpmyadmin returns this error:
MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Declare var int; Set var = SELECT COUNT(*) FROM friends WHERE ((user1 = id1 A' at line 1
note - i did it via phphmyadmin so i have
This is my code:
Declare var int;
Set var = SELECT COUNT(*) FROM friends WHERE ((user1 = id1 AND user2=id2) OR (user1 = id2 AND user2=id1));
IF var = 0
BEGIN
INSERT INTO friends
( user1, user2,pending)
VALUES (id1, id2,1);
Print 'Data now added.';
END
ELSE
BEGIN
Print 'Dah! already exists';
END
Try to invert those 2 lines :
...
declare #var int
AS
...
As follow :
...
AS
declare #var int
...
1) Everything (including declarations) must be in a BEGIN ... END block.
2) You don't need to (and cannot) declare #session_veriables, only local_variables.
3) Missing parameters. They must be declared between parantheses: proc_name(p1 INT, p2 INT)
4) All statements must terminate with ;
5) The whole procedure should be wrapped inside:
DELIMITER ||
...
||
DELIMITER ;
unless you send it via phpMyAdmin.

Mysql stored procedure syntax

I am trying to write simple mysql stored procedure and it seems that I can't get it right, so far I have
delimiter //
create procedure addRecord(_login varchar(15),_artist varchar(50),_record varchar(50))
begin
declare dbArtist varchar(50);
delcare dbRecord varchar(50);
set dbArtist = (select artistname from artists where lower(artistname) = lower(_artist));
set dbRecord=(select recordname from records where lower(recordname)=lower(_record));
if not exists (select * from Artists where lower(artistname)=lower(_artist)) then
begin
INSERT INTO `Artists`(`ArtistName`) VALUES (_artist);
set dbArtist=_artist;
end
if not exists (select * from Records as R inner join Artists as A on R.ArtistId=A.ArtistId where lower(R.RecordName)=lower(_record) and A.ArtistName=dbArtist) then
begin
INSERT INTO `Records`(`ArtistId`, `RecordName`) VALUES ((select artistid from artists where artistname=dbArtist),_record);
set dbRecord=_record;
end
end
but I get syntax error in line 4:
#1064 - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'dbRecord varchar(50);
set dbArtist = (select artistname from artists where lowe' at line 4
this message error was returned to me by phpMyAdmin, can anyone tell me why do I get an error?
edit: modified version, still not good
delimiter //
create procedure addRecord(_login varchar(15),_artist varchar(50),_record varchar(50))
begin
declare dbArtist varchar(50);
declare dbRecord varchar(50);
set dbArtist = (select artistname from artists where lower(artistname) = lower(_artist));
set dbRecord=(select recordname from records where lower(recordname)=lower(_record));
if not exists (select * from Artists where lower(artistname)=lower(_artist)) then
begin
INSERT INTO `Artists`(`ArtistName`) VALUES (_artist);
set dbArtist=_artist;
end
if not exists
(select * from Records as R inner join Artists as A on R.ArtistId = A.ArtistId where lower(R.RecordName)=lower(_record) and A.ArtistName=dbArtist)
then
begin
INSERT INTO `Records`(`ArtistId`, `RecordName`) VALUES ( (select artistid from artists where artistname=dbArtist) ,_record);
set dbRecord=_record;
end
end
now error in line 14 and message:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if not exists (select * from Records as R inner join Artists as A on R.ArtistId' at line 14
The problem is that you misspelled DECLARE:
delcare dbRecord varchar(50);
UPDATE: For your next error, the problem is your illegal use of NOT EXISTS.
Within a stored procedure the proper approach is to count the existing rows, and then conditionally insert a value if the count is 0.
Something like this:
SELECT COUNT(*)
INTO #v_row_count
FROM Artists
WHERE LOWER(artistname)=LOWER(_artist);
IF (#v_row_count = 0)
THEN
INSERT INTO `Artists`(`ArtistName`) VALUES (_artist);
set dbArtist=_artist;
END IF;
P.S. To avoid poor performance on on your select query, you should consider using a collation that is not case-sensitive so you don't need to apply the LOWER() function to the artistname column.