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.
Related
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!
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().
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
I'm working with stored procedures in mysql, so I have the following procedure:
DELIMITER ##
DROP PROCEDURE IF EXISTS generarEstadisticoRD ##
CREATE PROCEDURE generarEstadisticoRD ( mesInicial INT,anualInicial INT, mesFinal INT,anualFinal INT, codigoEntidad CHAR(3),mes INT )
BEGIN
DECLARE controlador INT;
DECLARE tipoDocumento CHAR(2);
DECLARE cursorDocumentos CURSOR FOR SELECT DISTINCT e.claseDocIdentidadFallecido
FROM EstadisticoRD e WHERE e.anual>=anualInicial AND e.anual<=anualFinal
AND e.mes >=mesInicial AND e.mes<=mesFinal AND e.codOficina=codigoEntidad;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET controlador = 1;
DROP TEMPORARY TABLE IF EXISTS estadistico;
CREATE TEMPORARY TABLE IF NOT EXISTS
estadistico( TIPO CHAR(2), MES INT );
OPEN cursorDocumentos;
cursorLoop : LOOP
FETCH cursorDocumentos INTO tipoDocumento;
IF( controlador=1 ) THEN
LEAVE cursorLoop;
END IF
/**
*Lógica
*/
INSERT INTO estadistico(`TIPO`,`MES`)
SELECT DISTINCT
c.descripcion,
IFNULL( (SELECT e.numRegistrosReportados FROM estadisticoRD e WHERE e.codOficina=codigoEntidad
AND e.claseDocIdentidadFallecido=tipoDocumento AND e.mes=mes ), 0)
FROM estadisticoRD e, claseDoc c WHERE e.codOficina=codigoEntidad AND e.claseDocIdentidadFallecido=tipoDocumento
AND c.claseDoc = e.claseDocIdentidadFallecido;
END LOOP cursorLoop;
CLOSE cursorDocumentos;
SELECT * FROM estadistico;
END ##
DELIMITER ;
I get the following messages when I try to execute the procedure:
Executed successfully in 0,001 s, 0 rows affected.
Line 2, column 1
Error code 1064, SQL state 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 'INSERT INTO estadistico(`TIPO`,`MES`)
SELECT DISTINCT c.descripcion,
' at line 24
Line 3, column 1
So, what am I doing wrong?.
UPDATE 1:
The I corrected the mistake with semicolon thanks #Daniel Victoria
But now I get the following mistake:
Error code 1267, SQL state HY000: Illegal mix of collations (latin1_spanish_ci,IMPLICIT) and (latin1_swedish_ci,IMPLICIT) for operation '='
Exactly I get this mistake when I do
SELECT DISTINCT e.claseDocIdentidadFallecido
FROM EstadisticoRD e WHERE ... AND e.codOficina=codigoEntidad;
why when I do e.codOficina=codigoEntidad I get this mistake, how to fixed it?.
UPDATE 2:
To solve it, I need to put COLLATE latin1_swedish_ci after to the column that has the mistake.
In this case the new query is :
SELECT DISTINCT *
FROM estadisticoRD e WHERE e.anual>=anualInicial AND e.anual<=anualFinal
AND e.mes >=mesInicial AND e.mes<=mesFinal AND e.codOficina = codigoEntidad COLLATE latin1_swedish_ci;
I hope to finish this procedure the best way.
Your are missing a semicolon (;) after the "END IF"
I cannot understand why the following SQL procedure will not store on my database and is reporting an error, I've been at it for ages and am totally puzzled.
DELIMITER $$
CREATE PROCEDURE add_brand(IN inBrandName TEXT)
BEGIN
DECLARE brandexists INT DEFAULT 0;
SELECT count(*) WHERE BrandName = inBrandName INTO brandexists;
IF brandexists = 1 THEN
select "exists";
ELSE
INSERT INTO tblBrand (BrandName) VALUES (inBrandName);
SELECT LAST_INSERT_ID();
END IF;
END
The error i'm getting is this:
#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 'WHERE BrandName = inBrandName INTO brandexists; IF brandexists = 1 THEN sele' at line 6
any ideas?
You are missing a table where you select from:
SELECT count(*) WHERE BrandName = inBrandName INTO brandexists;
^---here (from some_table)