Show message in stored procedure - mysql

How do I show a message from a stored procedure?
What is the right syntax to display a message saying whether or not rows exist?
In SQL Server it's PRINT to show a message bat in WORKBENCH...
CREATE PROCEDURE `new_proced` (
in myid int(3)
)
BEGIN
if not exists (select id from table where id = myid)
then
show message 'Row no exists';
else
show message 'Row exists';
end if;
END

Not entirely sure why you would want to do something like that, but you could do something like this:
...
then
select 'YOUR MESSAGE HERE'
else
select 'YOUR OTHER MESSAGE HERE'
end if
Or you could select 1 or 0, might be a little better...

There is no Proper output statement provide in MySQL like in Oracle, we have DBMS_OUTPUT.PUT_LINE. So, to display any messages on the console, you can use SELECT statement as:
SELECT message;
Eg:
SELECT "WELCOME TO MySQL";

For debugging info from stored procedure in MySQL,there are following options through which you can do this.
1.Write into the file externally:
select "your_message" as log into outfile '/temp/brajesh.txt';
2.Use select command to print message:
select "result_message";
3.Use select command to print additional information with message:
select concat("Hello ! :", result);
4.Create addition table temp and push all message into it:
insert into temp select concat(result);
Example
drop procedure if exists display_name_procedure;
delimiter //
create procedure display_name_procedure(IN name_val varchar(65))
begin
declare result varchar(65);
set result := display_name_function(name_val);
create table if not exists temp (name_val varchar(65) not null);
insert into temp select concat(result);
select "penguin" as log into outfile '/temp/brajesh.txt';
select concat("Hello ! :", result);
end//
delimiter ;

DELIMITER //
create procedure
insert_data_student1(student_name varchar(50),email varchar(50),group_id int)
begin
if not exists(select email from student where email="email")
then
insert into student(student_name,email,group_id) values (student_name,email,group_id);
else
select 'all reday exists';
end if;
end //
DELIMITER ;

Related

Does MySQL have a “print” function to show custom text output?

I want MySQL outputting a sentence to describe the query results before outputting query results. How to do it?
For example, I want to write a procedure to query information about students with specific names,the name will be passed as argument to the procedure.
this is my snippet of my procedure :
delimiter $$
create procedure show_specific(in student_name text)
begin
declare b_count int default 0;
select count(*) into b_count from students where students.name=student_name;
if(b_count=0)
then select 'Not found';
else
select*
from students where students.name = student_name
end if;
end $$
delimiter ;
Maybe this is not a good example... In this example, if the b_count is zero, this procedure will output 'Not found'. I can use 'print' in SQL server. However MySQL doesn't have 'print' function, Is there similar function in MySQL?
It would help if you described why you want to do this. I don't believe there is any completely equivalent feature in mysql. You can return a warning that the client can see with SHOW WARNINGS by doing:
signal sqlstate '01000' set message_text='message to client';
You just select it:
select 'hello world' as greetings

MySQL: Insert with conditional

I must perform the following situation down, but when you run got the error:
SQL 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 'INTO produto_seriais(serial_id) VALUES( SELECT id
FROM seriais WHERE serial =' at line 5
SELECT CASE WHEN (
SELECT COUNT(id) FROM seriais WHERE serial = '2020'
) > 1
THEN
(INSERT INTO produto_seriais(serial_id) VALUES(
SELECT id FROM seriais WHERE serial = '2020'
))
ELSE (
INSERT INTO seriais (serial) VALUE('2020');
SET #last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO produto_seriais (serial_id) VALUES (#last_id_in_table1);
)
END;
The case is as follows:
I'll get in "serial" table by serial "X". If it already exists, unless your ID in the "produto_seriais" table. If there is (serial), I will save the same, recover your ID and save to "produto_seriais". Any suggestions for how to do this?
Important Note: This routine will run will be thousands of times each execution (10,000 or more, depending on the quantity of serial).
P.s.: Sorry for my bad english.
Try a stored procedure
DELIMITER //
CREATE PROCEDURE sp_produto_seriais(IN `p_serial_id`)
IF EXISTS (SELECT * FROM seriais WHERE serial = p_serial_id )
BEGIN
INSERT INTO produto_seriais (serial_id)
SELECT id
FROM seriais
WHERE serial = p_serial_id
END
ELSE
BEGIN
INSERT INTO seriais (serial) VALUE(p_serial_id);
INSERT INTO produto_seriais (serial_id) VALUES (LAST_INSERT_ID());
END //
DELIMITER ;
usage:
CALL sp_produto_seriais('2020')
You could use the if exists..else statement.
If exists (select * from ....)
Begin
Insert into ... Select id from table
End
Else
Begin
Insert..
End
Please fill .... with your statements. You could use the link here to convert it for MySQL.
Convert if exists for MySQL

MSQ can't DELETE from same tabel as it SELECTS - Need help for workaround in my DELETE TRIGGER

I wan't to make the trigger delete the row with the lowest ID, if it is recurring. And by recurring i mean the number and username are the same in two rows.
For example
ROW1: ID: 1 , Nr: 1 , UN: MVJ and
Row2: ID: 2 , Nr: 1 , UN: MVJ
Those are recurring, but if the 'Nr' or 'UN' were different, they wouldn't be.
But as the title explains, MYSQL can't do that, atleast with the way I've made my SQL Statement.
I'm open to solve the problem in an whole other way.
Drop trigger no_double_reservations;
DELIMITER !!
CREATE TRIGGER no_double_reservations
AFTER INSERT ON tilmeldte
FOR EACH ROW BEGIN
IF(
SELECT COUNT(*)
FROM tilmeldte
WHERE (kursus_nr, username)
IN (
SELECT kursus_nr, username
FROM tilmeldte
GROUP BY kursus_nr, username
HAVING COUNT(*) = 2
) = 2
)
THEN
DELETE FROM tilmeldte
Where tilmeldingsid = (
Select MIN(`tilmeldingsid`)
FROM tilmeldte
WHERE (kursus_nr, username)
IN (
SELECT MIN(kursus_nr), username
FROM tilmeldte
GROUP BY kursus_nr, username
HAVING COUNT(*) = 2
)
);
END IF;
END!!
DELIMITER ;
I hope you can help.
Since you haven't given any table definition, here is a logic how to get this done in MySQL.
create stored procedure that takes your username and kursus_id
check whether the username already exists
if yes > delete and insert new id
if no > just insert new record and send message back
in code it would be something like.
CREATE PROCEDURE `SP_NEW_RESERVATION` (in iUsername varchar(50), in iKursus_id int)
BEGIN
DECLARE EXIT HANDLER for sqlexception
BEGIN
rollback;
SELECT 'False' as Result, 'Some error description or diagnose description from mysql' as `Description`;
END;
Start Transaction;
SET #mExists := (SELECT ID from tbl_yourTable where ((kursus_id = iKursus_id) and (username like iUsername)));
if (length(coalesce(#mExists,'')) <> 0) then
-- username does not exists so you can continue with insert a new reservation
insert into tbl_yourTable and continue here
-- send back message
SELECT 'True' as Result, 'New record inserted') as `Description`;
ELSE
-- username exists already and the id would be saved in mExists so delete the id and continue with your insert_method
Delete from Tbl_yourtable where id = #mExists something ligke that;
insert into tbl_yourtable .....
-- you can send back a message like
SELECT 'True' as Result, concat('Old record(', #mExists, ') Deleted and new record inserted') as `Description`;
end if;
Commit;
END
above code is incomplete. To execute this code you need to correct your insert and delete commands. Then just call the procedure like.
call SP_NEW_RESERVATION('KrishKm', 2);
if username 'KrishKm' already exists you will get message back like:
True, Old record(10) Deleted and new record inserted.
if not you get message back:
True, New record inserted.
if anything goes wrong you get message :
False, 'Some error description or diagnose description from mysql'
Good luck.

Multiple If conditions in a trigger

i want to write multiple if conditions to check the values of different columns of a same table in a trigger. i am checking for the two columns right now and i am getting the mysql error
#1064(syntax error) at Line # 17.
following are my conditions. plz help me what im doing wrong.
IF (OLD.CE_EN_OPTION_ID != NEW.CE_EN_OPTION_ID)
THEN
INSERT INTO audit_log(
BENEFICIARY_ID ,
TABLE_NAME ,
FIELD_NAME ,
OLD_VALUE ,
NEW_VALUE ,
EDIT_BY,
DATE_TIME
)
VALUES (
OLD.BENEFICIARY_ID, 'be_ce_main', 'CE_EN_OPTION_ID', OLD.CE_EN_OPTION_ID, NEW.CE_EN_OPTION_ID, NEW.EDITED_ID,NOW()
);
END IF;
IF(OLD.CE_DM_OPTION_ID != NEW.CE_DM_OPTION_ID)
THEN
INSERT INTO audit_log(
BENEFICIARY_ID ,
TABLE_NAME ,
FIELD_NAME ,
OLD_VALUE ,
NEW_VALUE ,
EDIT_BY,
DATE_TIME
)
VALUES (
OLD.BENEFICIARY_ID, 'be_ce_main', 'CE_DM_OPTION_ID', OLD.CE_DM_OPTION_ID, NEW.CE_DM_OPTION_ID, NEW.EDITED_ID,NOW()
);
END IF;
You are missing BEGIN - END block.
And I fear you did not override delimiter to instruct sql engine to not execute statements ending with default statement terminator ; semicolon. Because you didn't define new delimiter, sql engine assumed it was the end of statement at first found ; semicolon. There it failed because the statements are not in proper syntax order.
Try the following:
Delimiter //
CREATE TRIGGER 'test_trigger' AFTER UPDATE ON 'be_ce_main' FOR EACH ROW
BEGIN -- this is a must if you have more than one executable statements below
-- your trigger body here
END;
//
Delimiter ;
Refer to:
MySQL: Create Trigger Syntax

multiple value insert works in mysql procedures?

Multivalue insert example - it works manually but NOT in mySQL stored procedure.
INSERT INTO input_data1(mobile) VALUES (9619825525),(9619825255),(9324198256),(9013000002),(9999999450),(9999999876) ;
i am getting syntax error near "str" word in below proc, Can any one let me know how to implement this multi value INSERT work in procedure?
DELIMITER |
DROP PROCEDURE IF EXISTS mobile_series1;
CREATE PROCEDURE mobile_series1(IN str text)
LANGUAGE SQL READS SQL DATA
BEGIN
DROP TABLE IF EXISTS input_data1 ;
CREATE TEMPORARY TABLE input_data1 (mobile varchar(1000)) engine=memory;
INSERT INTO input_data1(mobile) VALUES str;
END |
DELIMITER ;
Thanks in Advance.
I don't have a MySQL server so there's probably syntax errors and +1 errors (i.e. may not be capturing the last on the list, may not progress past the first item etc, problems fixed by putting a +1 in the code), but you basically want to replace your INSERT statement with something this.
DECLARE INT _CURSOR 0;
DECLARE INT _TOKENLENGTH 0;
DECLARE VARCHAR _TOKEN NULL;
SELECT LOCATE(str, ",", _CURSOR) - _CURSOR INTO _TOKENLENGTH;
LOOP
IF _TOKENLENGTH <= 0 THEN
SELECT RIGHT(str, _CURSOR) INTO _TOKEN;
INSERT INTO input_data1(mobile) VALUE _TOKEN;
LEAVE;
END IF;
SELECT SUBSTRING(str, _CURSOR, _TOKENLENGTH) INTO _TOKEN;
INSERT INTO input_data1(mobile) VALUE _TOKEN;
SELECT _CURSOR + _TOKENLENGTH + 1 INTO _CURSOR;
SELECT LOCATE(str, ",", _CURSOR + 1) - _CURSOR INTO _TOKENLENGTH;
END LOOP;
Your function call would then be something like
EXEC mobile_series1('9619825525,9619825255,9324198256')