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

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

Related

select statement intermittently returns null

So I have the following code in a stored procedure:
set #Id = (select id from foo where Name = 'bar');
IF #Id is null THEN
#add missing record
END IF;
However, its seems that the database will only return a value intermittently. Even when I know my select statement will return a record (copied and pasted directly out of my stored proc). Has anyone else had this issue with MySQL?
about the only crazy thing my proc is doing:
DECLARE CONTINUE HANDLER FOR 1062, 1452
but neither of those should effect my query (I am sure there is one and only one record)
Thanks
You can use a stored procedure like the following:
CREATE PROCEDURE example_proc (pName VARCHAR(10))
BEGIN
IF NOT EXISTS(SELECT 1 FROM foo WHERE Name = pName) THEN
INSERT INTO foo (Name) VALUES (pName);
END IF;
END
demo on dbfiddle.uk
SO i don't know why this fixed the problem, but it did.
By setting the variable to null first before the assignment seems to have fixed the problem. I was have the problem intermittently, so maybe I'm just lucking out longer than I did last time.

Want to generate unique Id's using a function in mysql

I wrote a function to generate unique id's,its working but sometimes two people are getting same id,I mean duplicates are formed. My unique id looks like
2016-17NLR250001, I deal with only last four digits 0001. I am posting my function please correct it and please help me in avoiding duplicates even though users login into same account or if they do it on same time.
MY FUNCTION:
DELIMITER $$
USE `olmsap`$$
DROP FUNCTION IF EXISTS `fun_generate_uniqueid`$$
CREATE DEFINER=`root`#`%` FUNCTION `fun_generate_uniqueid`( V_DATE DATE,V_MANDALID INT ) RETURNS VARCHAR(30) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE MDLCODE VARCHAR(5);
SET MDLCODE = ' ';
SELECT COUNT(*) INTO #CNT FROM `st_com_mandal` WHERE MANDAL_VS_MC=V_MANDALID;
SELECT dist_mandal_code INTO MDLCODE FROM `st_com_mandal` WHERE MANDAL_VS_MC=V_MANDALID;
IF #CNT>0 THEN
SET #YR=`FUN_FISCAL_YR`(V_DATE);
SELECT CONCAT(IF(DIST_SAN_CODE='GUN','GNT',DIST_SAN_CODE),IFNULL(`dist_mandal_code`,'NULL'))INTO #MANDAL
FROM `st_com_dist` SCD INNER JOIN `st_com_mandal` STM ON STM.`mandal_dist_id`= SCD.`DIST_VC_DC` WHERE MANDAL_VS_MC=V_MANDALID;
IF MDLCODE >0 THEN
SELECT COUNT(Soil_Sample_ID)+1 INTO #ID FROM `tt_mao_soil_sample_dtls` WHERE MANDAL_ID=V_MANDALID AND SUBSTR(UNIQUE_ID,1,7)=#YR ;
ELSE
SELECT COUNT(Soil_Sample_ID)+1 INTO #ID FROM `tt_mao_soil_sample_dtls` WHERE SUBSTR(UNIQUE_ID,1,14)=CONCAT(#YR,#MANDAL) ;
END IF ;
IF LENGTH(#ID)=1 THEN
SET #ID=CONCAT('000',#ID);
ELSEIF LENGTH(#ID)=2 THEN
SET #ID=CONCAT('00',#ID);
ELSEIF LENGTH(#ID)=3 THEN
SET #ID=CONCAT('0',#ID);
ELSE
SET #ID=#ID;
END IF ;
RETURN CONCAT(#YR,#MANDAL,#ID);
ELSE
RETURN 'Mandal Doesnt Exists';
END IF;
END$$
DELIMITER ;
I do not think community will be able to help you with this question. This is a complex function that requires very careful analysis of table / index access and locking.
The only thing I can recommend is to not use existing table data to calculate next sequence as this is a bad practice.
Besides Race conditions that you are experiencing you will also get problems if the record with the last sequence is deleted.
I suggest you read this to get an idea on how to write a custom sequence generator:
http://en.latindevelopers.com/ivancp/2012/custom-auto-increment-values/

Third-party stored procedure returns value on select and it stops my own stored procedure

I'm designing a Stored Procedure which does a lot of things, some of them covered for third-party SPs that I cannot edit because they're hugely used on other places of the app I'm developing. I'll simplify my code in order to explain my problem a little easier:
My code is the following:
DELIMITER ;;
CREATE PROCEDURE `my_own_sp`(
IN my_param INT(11),
OUT my_returned_value INT(11),
OUT logger TEXT
)
BEGIN
SET logger = "echo off";
CALL third_party_SP(my_param);
SET logger = "half way!";
CALL another_third_party_SP(my_param);
SELECT id_user INTO my_returned_value FROM main_Table WHERE id_param = my_param;
SET logger = "This is the end...";
END;;
DELIMITER ;
both third party SPs would be like the following, they don't return any value but they modify some tables and records and then they make a SELECT in order to receive the result in PHP:
DELIMITER ;;
CREATE PROCEDURE `third_party_SP`(
IN my_param INT(11)
)
BEGIN
-- Do a lot of magic between tables
SELECT * FROM secondary_table WHERE id_param = my_param;
END;;
DELIMITER ;
But when I execute my SP, instead of receiving the value of my_returned_param and logger = "This is the end...", I receive the select of third_party_SP (I'm not even receiving logger = "half way!". It seems to me that the execution of my_own_sp stops once it receives a returned value, but this value is the last select of third_party_SP.
So the question is: can I handle the returned select of third_party_SP so I can keep working? or maybe there's another way to call third_party_SP in order to avoid the returned select?
Thank you very very much

Show message in stored procedure

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 ;

MySQL: IF / THEN statements in stored procedures

I'm writing a stored procedure that uses multiple IF / THEN statements that also need to execute multiple queries if they evaluate to true. Problem is, I can't seem to find any examples of the appropriate syntax. From the MySQL dev handbook, it seems like I could have multiple queries in the "statement_list," but so far I can't get it to work.
Here's what I'm trying to do:
SET agency =
COALESCE((SELECT org_agency_o_id
FROM orgs_agencies
WHERE org_agency_code = maj_agency_cat)
,(SELECT min(org_id)
FROM orgs
WHERE org_name LIKE CONCAT('U.S.',SUBSTRING(maj_agency_cat,5))))
IF agency IS NULL THEN
-- execute multiple queries
INSERT INTO orgs (org_name
,org_name_length
,org_type
,org_sub_types)
VALUES (CONCAT('U.S. ',SUBSTRING(maj_agency_cat,5))
,LENGTH(CONCAT('U.S. ',SUBSTRING(maj_agency_cat,5)))
,'org','Org,GovernmentEntity,Federal,Agency');
SET agency = LAST_INSERT_ID();
END IF;
The error:
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 agency IS NULL THEN
INSERT INTO orgs (org_name,org_name_length,org_type,' at line 53
Any ideas? I know it has to be something simple, so I would greatly appreciate anybody's input.
You got a few issues as far as I can see:
As David pointed out, each and every statement needs to be terminated by a ;
If you do a SELECT, better make sure it can only select one value by doing a LIMIT 1; If you've got an aggregate function like min() then only one value can come out.
If you writing the procedure using the CREATE PROCEDURE ... syntax, don't forget to set DELIMITER $$ before the CREATE PROCEDURE ... END $$ body and a DELIMITER ; after.
If you have multiple statements inside your IF THEN ... END IF block, it's a good idea to put them inside a BEGIN ... END; block.
If you have a return value, like agency here, why not make it a FUNCTION name (arg1: INTEGER) RETURNS INTEGER instead of a PROCEDURE name (IN arg1 INTEGER, OUT agency INTEGER). The function is much more versatile.
DELIMITER $$
CREATE PROCEDURE name(arg1 INTEGER, arg2 INTEGER, ...)
BEGIN
SELECT SET agency =
COALESCE((SELECT org_agency_o_id
FROM orgs_agencies
WHERE org_agency_code = maj_agency_cat) LIMIT 1,
(SELECT min(org_id) FROM orgs
WHERE org_name LIKE CONCAT('U.S.',SUBSTRING(maj_agency_cat,5))));
IF agency IS NULL THEN BEGIN
-- execute multiple queries
INSERT INTO orgs (org_name
,org_name_length
,org_type
,org_sub_types)
VALUES (CONCAT('U.S. ',SUBSTRING(maj_agency_cat,5))
,LENGTH(CONCAT('U.S. ',SUBSTRING(maj_agency_cat,5)))
,'org','Org,GovernmentEntity,Federal,Agency');
SET agency = LAST_INSERT_ID();
END; END IF;
END $$
DELIMITER ;
No semicolon after your first SET statement.