hope everything is going great with you, I'm facing a problem with stored procedure, get to the chase, here's the code :
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `register`(in un varchar(45),in pw varchar(45),
in user_email varchar(45),
in permissionid int,in targeted_table varchar(15))
begin
declare id int;
declare target_table varchar(15);
set target_table = targeted_table;
insert into user_authentication(user_name,user_password,email,permission_id)
values(un,pw,user_email,permissionid);
select user_id into id
from user_authentication
where user_name = un;
insert into target_table(user_id)values(id) ;
end
whenever I call the SP through this statement :
call register('abeer','somePassword','someEmail',1,'job_seeker')
workbench shouts at me coming out with this exception :
Error Code: 1146
Table 'recruitment.target_table' doesn't exist
In fact It commits the first insertion statement in the SP, but when It reaches the select statement, I got the exception above, though I'm dead sure the table,job_seeker, is there, can't you just tell me what goes wrong with my SP, for this is the first time using multiple statements inside SP, variables too, thank you .
You have coded a literal for the table name - you want mysql to evaluate the variable, then execute it as dynamic sql. Here's how you do it:
PREPARE mycmd from CONCAT('insert into ', target_table, '(user_id) values(', id, ')');
EXECUTE mycmd;
Related
Consider the following stored procedure and its usage:
DROP PROCEDURE IF EXISTS ShowMIHoles;
DELIMITER $$
CREATE PROCEDURE ShowMIHoles(IN CourseID VARCHAR(255))
BEGIN
select * from tblcourses where id=CourseID;
END $$
DELIMITER ;
call ShowMIHoles(1299)
That works, and returns the row of table tblcourses with id 1299.
However, it isn't protected from SQL injection.
So, I read that quote() should be used to make a value safe.
This is my attempt to use quote:
DROP PROCEDURE IF EXISTS ShowMIHoles;
DELIMITER $$
CREATE PROCEDURE ShowMIHoles(IN CourseID VARCHAR(255))
BEGIN
select * from tblcourses where id=quote(CourseID);
END $$
DELIMITER ;
call ShowMIHoles(1299)
That results in "0 rows returned". No error message. MySQL 5.7.28.
I tried various tests to see what was going wrong. The ones that don't use CourseID parameter, I tested both inside procedure, and as a stand-alone query.
select quote(1299);
=> '1299'
select * from tblcourses where id='1299';
=> The expected row with id 1299.
select * from tblcourses where id=quote(1299);
=> 0 rows returned.
It is possible to make this work, via prepared statement:
...
BEGIN
SET #sql = CONCAT('select * from tblcourses where id=', quote(CourseID));
prepare stmt from #sql;
execute stmt;
END $$
...
=> The expected row with id 1299.
Question:
Is there any way to safely use this parameter as an expression value in the where clause, without dynamically preparing a statement?
You do not need to worry about SQL injection inside a stored procedure unless you are using dynamic SQL. Strings will always be treated like whole string and numbers as numbers.
So, the first version you are showing is perfectly fine. Just make sure that when you call the procedure, your code is safe.
I have the following table created in mysql database.
create table stud_info(Student_ID int,Name varchar(10),Class varchar(10),Marks int)
I have also created a stored procedure to retrieve the name given the id like below:
DELIMITER //
create procedure selectEmp2(IN num1 INT,OUT name varchar(20))
BEGIN
select Name INTO name from myDB.stud_info where Student_ID=num1;
END//
When I am calling the stored procedure , I am getting null value. Please let me know where I am going wrong.
I think your stored procedure should work, but I would advise giving names to parameters that are likely to be unique. I also prefer explicit variable assignment, because select into can mean different things. Does this work?
DELIMITER //
create procedure selectEmp2(IN in_num1 INT, OUT out_name varchar(20))
BEGIN
select si.Name into out_name
from myDB.stud_info si
where si.Student_ID = in_num1;
END;//
Try this:
DELIMITER //
create procedure selectEmp2(IN _num1 INT,OUT _name varchar(20))
BEGIN
select Name INTO _name
from myDB.stud_info
where Student_ID=_num1;
END//
I'm using sybase powerbilder12 IDE and mySQL.
I have a stored procedure like this:
DELIMITER //
CREATE PROCEDURE CRTempTable(IN loc_code CHAR(6))
BEGIN
create temporary table mstparameter (select * from mstparameter_consolidate where location_code = 'loc_code');
END//
DELIMITER ;
I'm calling it in the powerbuilder12 like this:
DECLARE TempTBCRCall PROCEDURE FOR TempTableCR
location_code = :gs_location_code_mstparameter ;
execute TempTBCRCall;
It gives me the error :
Stored procedure execution failure1054 SQLSTATE = S0022
[MySQL][ODBC 5.2(a) Driver][mysqld-5.5.25a]Unknown column
'location_code' in 'field list'... Error Code 0
but location_code is there in my mstparameter_consolidate table.
If I set to enter the location_code manually it works fine.
This is an example that works, I hope it helps you.
DECLARE pb_acceso_usuario PROCEDURE FOR SP_ACCESO_VALIDA_DATOS_USUARIO (:gs_cod_usuario,:ls_password);
execute pb_acceso_usuario;
if SQLCA.sqlcode = 0 then
FETCH pb_acceso_usuario INTO :ln_count,:gs_des_usuario,:ls_estado;
CLOSE pb_acceso_usuario;
end if
try putting "table-name." in front of the column-name.
I've written a stored procedure. It's working fine except taking the table name as input parameter.
Let see my proc in MySQL:
DELIMITER $$
USE `db_test`$$
DROP PROCEDURE IF EXISTS test_proc$$
CREATE DEFINER=`root`#`localhost`
PROCEDURE `test_proc`(IN serviceName VARCHAR(10),IN newsInfoTable VARCHAR(100))
BEGIN
SELECT COUNT(*) FROM newsInfoTable WHERE newsServiceName=serviceName;
END$$
DELIMITER ;
Stored procedure calling parameters:
USE db_test;
CALL test_proc('abc','tbl_test_news');
Here the service name parameter is working fine. But if I include the newsInfoTable variable as table input parameter then a error shows.
Table 'db_test.newsinfotable' doesn't exist
Why does this happen only for table parameter? How can I retrieve from this error or
How I pass a table name into a stored procedure as a parameter?
An SP cannot be optimized with a dynamic table name, so many DBs, MySQL included, don't allow table names to be specified dynamically.
One way around this is to use Dynamic SQL.
CREATE DEFINER=`root`#`localhost` PROCEDURE `test_proc`(IN serviceName VARCHAR(10),IN newsInfoTable VARCHAR(100))
BEGIN
SET #sql = CONCAT('SELECT COUNT(*) FROM ',newsInfoTable,' WHERE newsServiceName=?;');
PREPARE s1 from #sql;
SET #paramA = serviceName;
EXECUTE s1 USING #paramA;
END$$
You can use EXECUTE IMMEDIATE for a "less is more" solution (for me, less code = good)
CREATE PROCEDURE test_proc(IN serviceName VARCHAR(10), IN newsInfoTable VARCHAR(100))
BEGIN
EXECUTE IMMEDIATE CONCAT('SELECT COUNT(*) FROM ',newsInfoTable,' WHERE newsServiceName=''', serviceName, '''');
END
that part of a query cannot be dynamic.
you may consider implementing as a string that is executed dynamically at runtime
Although may not be what you want, alternatively, can consider to use conditionally if and prepare the statement.
DELIMITER $$
CREATE PROCEDURE select_count(IN table_name VARCHAR(20))
BEGIN
IF table_name = 'xxx' THEN
SELECT * FROM xxx;
ELSEIF table_name = 'yyy' THEN
...
ENDIF
END$$
I am trying to make a stored procedure using mySQL. This procedure will validate a username and a password. I'm currently running mySQL 5.0.32 so it should be possible to create procedures.
Heres the code I've used. All I get is an SQL syntax error.
GO
CREATE PROCEDURE checkUser
(IN #brugernavn varchar(64)),IN #password varchar(64))
BEGIN
SELECT COUNT(*) FROM bruger WHERE bruger.brugernavn=#brugernavn AND bruger.pass=#Password;
END;
Thank you in advance
I figured it out now. Here's the correct answer
CREATE PROCEDURE checkUser
(
brugernavn1 varchar(64),
password varchar(64)
)
BEGIN
SELECT COUNT(*) FROM bruger
WHERE bruger.brugernavn=brugernavn1
AND bruger.pass=password;
END;
# points to a global var in mysql. The above syntax is correct.
(IN #brugernavn varchar(64)**)**,IN #password varchar(64))
The problem is the )
Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.
DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;
In the above example ,database and table names are student_database and student respectively.
Note: Instead of s_name, you can also pass #s_name as global variable.
How to call procedure?
Well! its very easy, simply you can call procedure by hitting this command
$mysql> CAll getStudentInfo('pass_required_name');