stored procedure with count(*) and if statement - mysql

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.

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!

MySQL script error

I'm new to SQL programming and I decided to make a script. This one might be quite riddled with errors but I'm getting an error that I'm unable to resolve.
DELIMITER $
DROP FUNCTION IF EXISTS crossref$
CREATE FUNCTION crossref()
BEGIN
DECLARE i INT;
DECLARE names VARCHAR(70);
SET i = 1;
myloop: LOOP
SET i=i+1;
IF i = 6 then
LEAVE myloop;
END IF;
SET names = (SELECT NAME FROM cbase_excel_table WHERE ID = i);
INSERT INTO cbase_master(NAME, PERMALINK, HOMEPAGE_URL, CATEGORY_LIST, MARKET, FUNDING, 'STATUS', COUNTRY, REGION, CITY)
SELECT NAME, PERMALINK, HOMEPAGE_URL, CATEGORY_LIST, MARKET, FUNDING, 'STATUS', COUNTRY, REGION, CITY FROM cbase_excel_table WHERE ID = i;
UPDATE cbase_master
SET DESCRIPTION = (SELECT DESCRIPTION FROM cbase_json_table WHERE NAME = names)
SET DOMAIN = (SELECT DOMAIN FROM cbase_json_table WHERE NAME = names)
SET IMAGE_URL = (SELECT IMAGE_URL FROM cbase_json_table WHERE NAME = names)
SET FACEBOOK_URL = (SELECT FACEBOOK_URL FROM cbase_json_table WHERE NAME = names)
SET TWITTER_URL = (SELECT TWITTER_URL FROM cbase_json_table WHERE NAME = names)
SET LINKEDIN_URL = (SELECT LINKEDIN_URL FROM cbase_json_table WHERE NAME = names)
SET CBASE_UUID = (SELECT CBASE_UUID FROM cbase_json_table WHERE NAME = names);
END LOOP myloop;
END$
DELIMITER;
and I'm getting:
#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 'BEGIN
DECLARE i INT;
DECLARE names VARCHAR(70);
SET i = 1;
Any help?
An example of a function which shows a major difference to your function:
CREATE FUNCTION `fnFindMaximum`(`a` INT, `b` INT)
/* Before the BEGIN statement there are other things going on - the most important being the return type statement */
RETURNS int(11)
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE returnval INTEGER;
IF a >= b THEN
SET returnval = a;
ELSE
SET returnval = b;
END IF;
RETURN returnval;
END
Your function then goes on to manipulate sql but does not return a value so, as was pointed out by #arkhil, use a StoredProcedure in preference to a function.

Query always returns 1064 syntax error

I use 'MariaDB 5.5 x64' and Client HeidiSQL.
server environment is Windows Server2012 Datacenter.
And database use_progress a row is following
int id //auto-incremental primary key
int owner //owner user's unique id
varchar[20] name //key
int value //value
it stores online game user's states key-value type
for example
id owner name value
856 656 stage0cleared 0
857 656 have_gold 10214
858 657 inventory 22
and the next query's working test is fine
select count(*) from use_progress where owner = 656 and name = "inventory";
INSERT INTO use_progress (use_progress.owner, use_progress.name, use_progress.value) VALUES (656, 'inventory', 7);
UPDATE use_progress SET use_progress.value = 7 WHERE use_progress.`owner` = 656 AND use_progress.`name` = 'inventory';
but the next query is error 1064 (syntax error)
BEGIN
IF ((select count(*) from use_progress where owner = 656 and name = "inventory") = 0 ) THEN
INSERT INTO use_progress (use_progress.owner, use_progress.name, use_progress.value) VALUES (656, 'inventory', 7);
ELSE
UPDATE use_progress SET use_progress.value = 7 WHERE use_progress.`owner` = 656 AND use_progress.`name` = 'inventory';
END IF;
END
the error is folling next(always that error):
/* SQL error (1064): 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 'IF ((select count(*) from use_progress where owner = 656 and name = "inventory")' at line 2 */
I tried everything I could. Use () or not, insert dbname.tablename. prefix to every column name or not. But in every situation, the same error occurs.
I even tried this (line 2 is changed):
BEGIN
IF (1>2) THEN
INSERT INTO use_progress (use_progress.owner, use_progress.name, use_progress.value) VALUES (656, 'inventory', 7);
ELSE
UPDATE use_progress SET use_progress.value = 7 WHERE use_progress.`owner` = 656 AND use_progress.`name` = 'inventory';
END IF;
END
But same error occurs (message is same)
I don't know why this happen.
You can't use control structures like IF() THEN ... in simple queries, only in stored procedures or functions.
In this case you'd use a stored procedure. Try like this:
DELIMITER $$
CREATE PROCEDURE my_proc_name(IN p_owner int, IN p_name varchar(50), IN p_value int)
BEGIN
IF NOT EXISTS (select 1 from use_progress where owner = p_owner and name = p_name) THEN
INSERT INTO use_progress (owner, name, `value`) VALUES (p_owner, p_name, p_value);
ELSE
UPDATE use_progress SET `value` = p_value WHERE `owner` = p_owner AND `name` = p_name;
END IF;
END $$
DELIMITER ;
After creating it, you'd call it like this:
CALL my_proc_name(656, 'inventory', 7);

Issue with stored procedure and COUNT IF statement

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

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.