mySQL Stored Procedure for splitting strings by delimiter - mysql

I'm into writing a stored procedure which explodes a passed string by a
passed delimiter and returns the n-th element of the result. n is passed
too.
So this is what I came up with:
CREATE PROCEDURE SPLIT(IN strToSplit text, IN strDelimiter varchar(1), IN nPartToGet int,OUT strSlice varchar(255))
BEGIN
SET strSlice = replace(substring(substring_index(strToSplit, strDelimiter, nPartToGet),
length(substring_index(strToSplit,strDelimiter, nPartToGet - 1)) + 1), strDelimiter, '')
END
;
Sadly mysql keeps naging me that I've got an syntax error in there. IMHO this should work. Could anyone pls poke me on where I'm going wrong?
thanks in advance
K

You need to end your SET with a ';' and, given that the client interprets ; as the delimiter, you need to change the delimiter so you can enter an actual ; into the procedure.
mysql> delimiter //
mysql> CREATE PROCEDURE SPLIT(IN strToSplit text, IN strDelimiter varchar(1), IN nPartToGet int,OUT strSlice varchar(255))
-> BEGIN
-> SET strSlice = replace(substring(substring_index(strToSplit, strDelimiter,
-> nPartToGet), length(substring_index(strToSplit,strDelimiter,
-> nPartToGet - 1)) + 1), strDelimiter, '');
-> END
-> //
Query OK, 0 rows affected (0.01 sec)
mysql> delimiter ;
mysql> CALL SPLIT('1;2;3;4;5',';',3,#str);
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT #str;
+------+
| #str |
+------+
| 3 |
+------+
1 row in set (0.00 sec)
Relevant docs: http://dev.mysql.com/doc/refman/5.0/en/stored-routines.html

Related

How to call stored procedure and select the return value at a time on MySQL

on MySQL, I know I can use stored procedure something like this
call someProcedure(#return);
select #return;
but is there some way you can do it with single query ? like this
select #return from (call someProcedure(#return) as sp
thanks in advance :)
Define Procedure
mysql> DELIMITER //
mysql> CREATE PROCEDURE simpleproc(OUT param1 INT)
-> BEGIN
-> SELECT COUNT(*) INTO param1 FROM t;
-> END //
call the procedure ->
mysql> CALL simpleproc(#a);
Show Output ->
mysql> SELECT #a;
+------+
| #a |
+------+
| 3 |
+------+1 row in set (0.00 sec)

sql if-else procedure prob, cant create procedure

delimiter//
create procedure exercise(out stat char(10),out fee double)
begin
if stat=='AC executive' then set fee=100;
else if stat=='AC Economi' then set fee=50;
else set saldo=20;
end if;
end//
delimiter;
Your if-else if is not correct it should be
if condition then do something
elseif condition then do something
else do something
There is no space between elseif. Also I suppose you mean fee not saldo in the else part. And out stat char(10) should be in stat varchar(100), since you are using the param as input
delimiter //
create procedure exercise(in stat varchar(100),out fee double)
begin
if stat ='AC executive' then set fee=100;
elseif stat = 'AC Economi' then set fee=50;
else set fee=20;
end if;
end;//
delimiter;
Here is a test on mysql
mysql> delimiter //
mysql> create procedure exercise(in stat varchar(100),out fee double)
-> begin
-> if stat ='AC executive' then set fee=100;
-> elseif stat = 'AC Economi' then set fee=50;
-> else set fee=20;
-> end if;
-> end;//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> call exercise('AC executive',#o);
Query OK, 0 rows affected (0.00 sec)
mysql> select #o ;
+------+
| #o |
+------+
| 100 |
+------+
1 row in set (0.00 sec)

MYSQL stored procedure not checking the where clause and returning entire table

CREATE DEFINER=`root`#`localhost` PROCEDURE `Viewuser`(IN `userID` VARCHAR(50))
BEGIN
SELECT * FROM `tbl_userdetails` WHERE `UserID`=userID;
END
In the above code the user details of given user id should be return. But it returning the entire table while i execute this stored procedure.
try this method:
mysql> delimiter //
mysql> CREATE PROCEDURE simpleproc (OUT param1 INT)
-> BEGIN
-> SELECT COUNT(*) INTO param1 FROM t;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> CALL simpleproc(#a);
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT #a;
+------+
| #a |
+------+
| 3 |
+------+
1 row in set (0.00 sec)
https://dev.mysql.com/doc/refman/5.5/en/create-procedure.html
Got the answer. The field name in table should not be same as variable name.. That is the problem
CREATE DEFINER=root#localhost PROCEDURE Viewuser(IN ID VARCHAR(50))
BEGIN
SELECT * FROM tbl_userdetails WHERE UserID=ID;
END
This is working fine

Mysql Triggers, declare a variable and use it as column name

I have the table "mytable" that contains the "columnname" field wich is the name of a column in mytable2.
I use this one for the selection:
SET #DptScn = (SELECT columnname FROM mytable WHERE tablename = 'CustomTableName' AND fieldlabel = 'CustomField');
SET #identifiedid=144;
but, when I try:
SELECT #DptScn FROM mytable2 WHERE identifiedid = #identifiedid;
this give me NOT the content of the field but the name containted into variable #DptScn...
Any advice?
I can't use Prepared Statement because I'm in a Trigger...
UPDATE:
As suggested by spencer7593 I'm creating a procedure:
DROP PROCEDURE IF EXISTS p_t;
DELIMITER $$
CREATE PROCEDURE p_t (IN DptTcn VARCHAR(255), IN tid INT, OUT tT INT)
BEGIN
SET #DptTcn = DptTcn;
SET #tid = tid;
SET #sql = CONCAT('SELECT #DptTcn FROM mytable3 WHERE tid = #tid');
PREPARE stmt FROM #sql;
EXECUTE stmt;
END$$
DELIMITER ;
Then I try it:
SET #DptTcn = (SELECT columnname mytable WHERE tablename = 'CustomTableName' AND fieldlabel = 'CustomField');
SET #identifiedid=145;
CALL proc_ticket(#DptTcn, #identifiedid, #DptT);
But I receive a:
#2014 - Commands out of sync; you can't run this command now
One option to consider is creating a PROCEDURE that makes use of prepared statements, and then calling the the stored procedure from the trigger.
The SQL statement you execute to get the value from a particular column MUST have the column_name specified in the SQL text; this can't be derived "dynamically" in the execution of the statement.
To achieve something like this, you'll need to run two separate statements; one to get the column_name; the second to "SELECT column_name FROM". And the MySQL provided mechanism for executing that second query is a prepared statement.
Followup
Here's an example. I tried to get this built in SQLFiddle, but wasn't able to get it working (it just hung. So, here's the output from a mysql command line client instead.
(All of the statements below use the same delimiter // because we can't use a semicolon as a delimiter for the stored procedure. In SQLFiddle, we have to use the same delimiter on all statements, and the // just happens to be one of the options in SQLFiddle.)
mysql> DELIMITER //
mysql> CREATE PROCEDURE foo(IN colname VARCHAR(255), IN id INT, OUT val VARCHAR(255))
-> BEGIN
-> -- handler for "Unknown column" and "No data" exceptions
-> DECLARE EXIT HANDLER FOR 1054, 1329 BEGIN SET val = NULL; END;
-> SET #sql = CONCAT('SELECT ',colname,' INTO #val FROM t WHERE id = ',id,' LIMIT 1');
-> PREPARE stmt FROM #sql;
-> EXECUTE stmt;
-> SET val = #val;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE t (id INT, attr VARCHAR(4), ball VARCHAR(4))//
Query OK, 0 rows affected (0.11 sec)
mysql> INSERT INTO t VALUES (1, 'abcd','efgh'),(2,'ijkl','mnop')//
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> CALL foo('attr',1,#attr_1)//
Query OK, 0 rows affected (0.00 sec)
mysql> CALL foo('attr',2,#attr_2)//
Query OK, 0 rows affected (0.00 sec)
mysql> CALL foo('ball',1,#ball_1)//
Query OK, 0 rows affected (0.00 sec)
mysql> CALL foo('ball',2,#ball_2)//
Query OK, 0 rows affected (0.00 sec)
mysql> CALL foo('attr',777,#err_bad_id)//
Query OK, 0 rows affected (0.00 sec)
mysql> CALL foo('badcol',1,#err_badcol)//
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT #attr_1
-> , #attr_2
-> , #ball_1
-> , #ball_2
-> , #err_bad_id
-> , #err_badcol//
+---------+---------+---------+---------+-------------+-------------+
| #attr_1 | #attr_2 | #ball_1 | #ball_2 | #err_bad_id | #err_badcol |
+---------+---------+---------+---------+-------------+-------------+
| abcd | ijkl | efgh | mnop | NULL | NULL |
+---------+---------+---------+---------+-------------+-------------+
1 row in set (0.00 sec)
mysql> DELIMITER ;
you should create a SP and give the column name.
create proc dbo.TestGetData(#DptScn nvarchar(256))
as
begin
set nocount on
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'SELECT #DptScn FROM mytable2 WHERE identifiedid = 144'
exec sp_executesql #SQL, N'#DptScn nvarchar(256)', #DptScn =#DptScn
end
Then
exec dbo.TestGetData 'Column1'

MySQL create stored procedure syntax with delimiter

I am trying to create a stored procedure in MySQL using a delimiter like this:
use am;
DELIMITER $$
CREATE PROCEDURE addfields()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE acc INT(16);
DECLARE validId INT DEFAULT 0;
END $$
DELIMITER ;
It gives me an error:
#1304 - PROCEDURE addfields already exists
What is the proper syntax for making a stored procedure with a delimiter and dropping it if it exists first?
Getting started with stored procedure syntax in MySQL (using the terminal):
1. Open a terminal and login to mysql like this:
el#apollo:~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
mysql>
2. Take a look to see if you have any procedures:
mysql> show procedure status;
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db | Name | Type | Definer | Modified | Created | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| yourdb | sp_user_login | PROCEDURE | root#% | 2013-12-06 14:10:25 | 2013-12-06 14:10:25 | DEFINER | | utf8 | utf8_general_ci | latin1_swedish_ci |
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
1 row in set (0.01 sec)
I have one defined, you probably have none to start out.
3. Change to the database, delete it.
mysql> use yourdb;
Database changed
mysql> drop procedure if exists sp_user_login;
Query OK, 0 rows affected (0.01 sec)
mysql> show procedure status;
Empty set (0.00 sec)
4. Ok so now I have no stored procedures defined. Make the simplest one:
mysql> delimiter //
mysql> create procedure foobar()
-> begin select 'hello'; end//
Query OK, 0 rows affected (0.00 sec)
The // will communicate to the terminal when you are done entering commands for the stored procedure. the stored procedure name is foobar. it takes no parameters and should return "hello".
5. See if it's there, remember to set back your delimiter!:
mysql> show procedure status;
->
->
Gotcha! Why didn't this work? You set the delimiter to // remember? Set it back to ;
6. Set the delimiter back and look at the procedure:
mysql> delimiter ;
mysql> show procedure status;
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db | Name | Type | Definer | Modified | Created | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| yourdb | foobar | PROCEDURE | root#localhost | 2013-12-06 14:27:23 | 2013-12-06 14:27:23 | DEFINER | | utf8 | utf8_general_ci | latin1_swedish_ci |
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)
7. Run it:
mysql> call foobar();
+-------+
| hello |
+-------+
| hello |
+-------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Hello world complete, lets overwrite it with something better.
8. Drop foobar, redefine it to accept a parameter, and re run it:
mysql> drop procedure foobar;
Query OK, 0 rows affected (0.00 sec)
mysql> show procedure status;
Empty set (0.00 sec)
mysql> delimiter //
mysql> create procedure foobar (in var1 int)
-> begin select var1 + 2 as result;
-> end//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> call foobar(5);
+--------+
| result |
+--------+
| 7 |
+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Nice! We made a procedure that takes input, modifies it, and does output. Now lets do an out variable.
9. Remove foobar, Make an out variable, run it:
mysql> delimiter ;
mysql> drop procedure foobar;
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter //
mysql> create procedure foobar(out var1 varchar(100))
-> begin set var1="kowalski, what's the status of the nuclear reactor?";
-> end//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> call foobar(#kowalski_status);
Query OK, 0 rows affected (0.00 sec)
mysql> select #kowalski_status;
+-----------------------------------------------------+
| #kowalski_status |
+-----------------------------------------------------+
| kowalski, what's the status of the nuclear reactor? |
+-----------------------------------------------------+
1 row in set (0.00 sec)
10. Example of INOUT usage in MySQL:
mysql> select 'ricksays' into #msg;
Query OK, 1 row affected (0.00 sec)
mysql> delimiter //
mysql> create procedure foobar (inout msg varchar(100))
-> begin
-> set msg = concat(#msg, " never gonna let you down");
-> end//
mysql> delimiter ;
mysql> call foobar(#msg);
Query OK, 0 rows affected (0.00 sec)
mysql> select #msg;
+-----------------------------------+
| #msg |
+-----------------------------------+
| ricksays never gonna let you down |
+-----------------------------------+
1 row in set (0.00 sec)
Ok it worked, it joined the strings together. So you defined a variable msg, passed in that variable into stored procedure called foobar, and #msg was written to by foobar.
Now you know how to make stored procedures with delimiters. Continue this tutorial here, start in on variables within stored procedures: http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/
Here is the sample MYSQL Stored Procedure with delimiter and how to call..
DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`#`%` PROCEDURE `sp_user_login`(
IN loc_username VARCHAR(255),
IN loc_password VARCHAR(255)
)
BEGIN
SELECT user_id,
user_name,
user_emailid,
user_profileimage,
last_update
FROM tbl_user
WHERE user_name = loc_username
AND password = loc_password
AND status = 1;
END $$
DELIMITER ;
and call by, mysql_connection specification and
$loginCheck="call sp_user_login('".$username."','".$password."');";
it will return the result from the procedure.
Here is my code to create procedure in MySQL :
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `procedureName`(IN comId int)
BEGIN
select * from tableName
(add joins OR sub query as per your requirement)
Where (where condition here)
END $$
DELIMITER ;
To call this procedure use this query :
call procedureName(); // without parameter
call procedureName(id,pid); // with parameter
Detail :
1) DEFINER : root is the user name and change it as per your username of mysql localhost is the host you can change it with ip address of the server if you are execute this query on hosting server.
Read here for more detail
I have created a simple MySQL procedure as given below:
DELIMITER //
CREATE PROCEDURE GetAllListings()
BEGIN
SELECT nid, type, title FROM node where type = 'lms_listing' order by nid desc;
END //
DELIMITER;
Kindly follow this. After the procedure created, you can see the same and execute it.
MY SQL STORED PROCEDURE CREATION
DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin
select * from users
where id=UserId ;
END $$
DELIMITER ;