MySQL Error 1064 : near NULL at line 1 - mysql

I have been trying to figure out what am i doing wrong in the beloe procedure
CREATE PROCEDURE `example`(IN col_n char(50),IN p_cont char(50),IN p_ud int)
BEGIN
set #S = CONCAT('select rn.emp_id as emp_id,controller,perma,permb,permc,permd,order from emp n
join resource_emp rn on rn.emp_id = n.emp_id
join resource r on r.resource_id = rn.resource_id
join u_resource ur on ur.resource_id = r.resource_id
join user u on u.u_id = ur.ur_id
join(
select title,min(order) as pr from emp n
join resource_emp rn on rn.emp_id = n.emp_id
join resource r on r.resource_id = rn.resource_id
join u_resource ur on ur.resource_id = r.resource_id
join user u on u.u_id = ur.ur_id
where u.u_id = ',#p_ud,' group by title)a on a.title = n.title and a.pr = order
where u.u_id = ',#p_ud,' n.con = ''',#p_cont,''' and ,#col_n,' = 1
group by n.title order by n.order');
PREPARE stmt1 FROM #S;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END
I'm trying to execute the procedure as below but having the error
call hop_thlc_t.auth('perma', 'submit', 2);
Error Code: 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 'NULL' at line 1
while this happens, i can still execute the same and get desired results by running the above procedure as a query by using below params
set #col_n ='perma';
set #p_cont = 'submit' ;
set #p_ud =2;
Any help to fix the issue is appreciated

Just take the # off of your variables that are procedure arguments, as Sami Kuhmonen suggests in a comment.
Local variables in stored procedures don't have # before the name. If you use a variable like #col_n it's not the same variable as col_n which is the variable for your procedure argument.
Variables with # are called Session Variables. They have a scope outside your stored procedure. You discovered you can set the value before calling your procedure. Likewise, if you set the value of this variable inside the procedure, it will still have that value after your procedure returns.
I posted a demo in my answer here: https://stackoverflow.com/a/41925146/20860
Unfortunately, there's an exception to every rule. When you use PREPARE, you must use a session variable. Local variables won't work for PREPARE.

Related

How to execute this query: SELECT table_row FROM table AS concat(sth, sth)? Returning error at the concat, MySQL

I have this MySQL procedure:
CREATE PROCEDURE Employee_Dilligence(IN No_Hours INT)
BEGIN
SELECT EmpName,employees.EmpID, Hours_Worked,
Dilligence(Hours_Worked/(TIMESTAMPDIFF(Day, StartDate, CURDATE())*No_Hours))
AS concat('Worked more than', No_Hours, 'Hours')
FROM company.employees INNER JOIN company.employee_project INNER JOIN company.projects
ON employees.EmpID = employee_project.EmpID AND employee_project.ProjID = projects.ProjID
WHERE projects.ProjID = ProjectID;
And it works correctly, except for one thing: the concat here:
AS concat('Worked more than', No_Hours, 'Hours')
I do not understand why, though. The error message I'm getting is:
Error Code: 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 '('Worked more than', No_Hours, 'hours per day')
FROM company.employees INNER JOIN c' at line 5
Yet it looks like I am using concat correctly, so how can I fix this problem? If I replace the problematic line with just:
AS N_Hours_Worked_Per_Day
then it works fine, but isn't as nice.
The expected output I want would look something like this:
Employee_Dilligence(2)
#COLUMN NAMES OF OUTPUT:
EmpName | EmpID | Hours_Worked | Worked more than 2 hours per day
Employee_Dilligence(3)
#COLUMN NAMES OF OUTPUT:
EmpName | EmpID | Hours_Worked | Worked more than 3 hours per day
You can't use CONCAT as an alias for a field in MySQL. The alias must be a string, this will be the field's name in your result.
To build an SQL that include a variable as a fieldname, you can use a prepared statement with the following:
DELIMITER $$
CREATE PROCEDURE Employee_Dilligence(IN No_Hours INT)
BEGIN
SET #sql = CONCAT('SELECT EmpName,employees.EmpID, Hours_Worked, Dilligence(Hours_Worked/(TIMESTAMPDIFF(Day, StartDate, CURDATE())*',No_Hours,')) AS "Worked more than', No_Hours, 'Hours" FROM company.employees INNER JOIN company.employee_project INNER JOIN company.projects ON employees.EmpID = employee_project.EmpID AND employee_project.ProjID = projects.ProjID WHERE projects.ProjID = ProjectID;');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
With this you first make your query as a string, then make a prepared statement from it, which can be executed by the server.
It seems you are doing a syntax error. please see blow how to use concate in query.
SELECT CONCAT(first_name, ' ', last_name) AS 'Name', dept FROM users;

Error while returning multiple ResulSets from a stored procedure in MySQL

Here's shortened script of my stored procedure:
DROP PROCEDURE IF EXISTS `GetVehicleDetails`;
DELIMITER //
CREATE PROCEDURE `GetVehicleDetails`(
IN `inRefNo` VARCHAR(30) COLLATE utf8mb4_general_ci,
IN `inSurveyType` VARCHAR(20) COLLATE utf8mb4_general_ci
)
BEGIN
DECLARE vehicleTypeID VARCHAR(2);
SET FOREIGN_KEY_CHECKS = OFF;
SELECT * FROM vehicle_details V
LEFT JOIN vehicle_types VT ON VT.TypeID = V.VehicleType
LEFT JOIN vehicle_makes VM ON VM.TypeID = V.VehicleType AND VM.MakeID = V.VehicleMake
LEFT JOIN vehicle_models VD
ON VD.TypeID = V.VehicleType AND VD.MakeID = V.VehicleMake AND VD.ModelID = V.VehicleModel
LEFT JOIN vehicle_variants VV
ON VV.TypeID = V.VehicleType
AND VV.MakeID = V.VehicleMake
AND VV.ModelID = V.VehicleModel
AND VV.VariantID = V.VehicleVariant
LEFT JOIN vehicle_body_types VB ON VB.BodyTypeID = V.TypeOfBody
LEFT JOIN vehicle_info_preinspection VP ON VP.RefNo = inRefNo
LEFT JOIN fuel_types F ON F.FuelTypeID = VP.Fuel
WHERE V.RefNo = inRefNo;
# Fetch Vehicle Type
SELECT VehicleType INTO vehicleTypeID FROM vehicle_details WHERE RefNo = inRefNo;
# Get details of body parts
IF vehicleTypeID = 1 THEN /* Personal Car */
SELECT * FROM body_parts_personal_car WHERE RefNo = inRefNo;
/*IF inSurveyType = 'preinspection' THEN
SELECT * FROM accessories_personal_car WHERE RefNo = inRefNo;
END IF;*/
ELSEIF vehicleTypeID = 4 THEN /* 2 Wheeler */
SELECT * FROM body_parts_2_wheeler WHERE RefNo = inRefNo;
ELSE
SELECT * FROM body_parts_commercial_vehicle WHERE RefNo = inRefNo;
END IF;
SET FOREIGN_KEY_CHECKS = ON;
END//
DELIMITER ;
Now, while executing the stored procedure with this statement:
CALL GetVehicleDetails('some ref no', 'interim-survey');
an error is being thrown:
Static analysis:
1 errors were found during analysis.
Missing expression. (near "ON" at position 25)
SQL query: Edit Edit
SET FOREIGN_KEY_CHECKS = ON;
MySQL said: Documentation
2014 - Commands out of sync; you can't run this command now
I have noticed that the stored procedure is throwing on second SELECT statement -
SELECT * FROM body_parts_personal_car WHERE RefNo = inRefNo;
in my case. Even if I write SELECT Now(); or SELECT vehicleTypeID; before it, the stored procedure throws the same error. If I comment this SELECT statement out, the stored procedure WORKS.
The same stored procedure works on localhost perfectly. I am using phpMyAdmin on remote server to maintain my database.
Any help please?
EDIT: I am receiving same problem in all stored procedures which have multiple SELECT statements to be returned back as ResultSet.
And, if I click Execute from the list of stored procedures in phpMyAdmin, the stored procedure executes. But if I invoke the stored procedure with CALL <proc_name()>;, the above error is displayed.
The "Commands out of sync" error usually indicates the client side error (results from the previous result set have not been processed and remain in the buffer).
If you are running the procedure from the phpMyAdmin, note that phpMyAdmin does not know to handle procedures returning multiple result sets. Try to run the command from MySQL command prompt and see if you get any errors.
The procedure itself looks ok, apart from unnecessary SET FOREIGN_KEY_CHECKS-commands (the procedure does not do any update/insert).
There problem was with one or more of tables involved in the procedure. Some queries and procedure calls inside a procedure were giving errors as "illegal mix of collations xxxxxxxx". I had to set COLLATIONS of all char/varchar/enum fields of tables and parameters of procedures giving errors to utf8mb4_general_ci.

Error Code: 1064 in stored procedure update

I am using a prepared statement to execute an update query but I am getting the following error.
Error Code: 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 'NULL' at line 1
Here is the query my prepared statement produces.
Declare update_table_stmt varchar(1024);
set #update_data = concat('update results_temp_tbl as t1 inner join data_temp_tbl as t2 on t2.suite_raw = t1.suite_raw set t1.`',#get_dataday,'` = ',#get_set_columns,';');
update results_temp_tbl as t1 inner join data_temp_tbl as t2 on t2.suite_raw = t1.suite_raw set t1.`17356` = concat(t2.path,'/',t2.filename);
PREPARE update_table_stmt FROM #update_data;
EXECUTE update_table_stmt;
DEALLOCATE PREPARE update_table_stmt;
If I copy the above query and run it, I get no errors. So I am unsure of how to solve the issue
*****update****
Still getting the error. I have adjusted the code so it now prints out the following.
update results_temp_tbl as t1 inner join data_temp_tbl as t2 on t2.suite_raw = t1.suite_raw set t1.`17356` = t2.filepath_name;
I figured it out. I was in a loop and the id was null

Unable to call a stored procedure

I'm learning mysql stored procedures and, as it turns out, I'm not so good at it for now. I want to create a stored procedure that selects some columns from different tables and, obviously, outputs the result. I have:
USE `usertable159`;
DROP procedure IF EXISTS `getDataFor`;
DELIMITER $$
USE `usertable159`$$
CREATE DEFINER=`michael`#`%` PROCEDURE `getDataFor`(IN COUNTRY VARCHAR(2), IN ASIN VARCHAR(20),IN FC VARCHAR(1))
BEGIN
SET #sql = "select p.price, p.sku, p.fulfillment_channel, GROUP_CONCAT(es.excludedSeller) excluded, r.excludeNonFeatured
FROM "+COUNTRY+"_products p
LEFT JOIN ("+COUNTRY+"_excludedSellers es, "+COUNTRY+"_excludeRules r)
ON p.seller_sku = es.seller_sku and p.seller_sku = r.seller_sku where p.ASIN = '" + ASIN + "' and p.fulfillment_channel = " + FC + ";
";
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;
From all the errors I expected when writing this... the one I get is surprising to me:
Error Code: 1054. Unknown column 'de' in 'field list'
This is how I call it:
call getDataFor(de, B000LNHB8A, 2);
The IN parameter COUNTRY is not in the selected columns, how does it come?
I also tried calling it with
call getDataFor('de', 'B000LNHB8A', '2');
which results in
Error Code: 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 '2' at line 1
You have several problems:
1) You cannot concatenate strings with + in MySQL. You must use the CONCAT() built-in function.
2) Your LEFT JOIN syntax is incorrect. It should be LEFT JOIN x ON ... LEFT JOIN y ON ....
3) You must quote your arguments. It looks like you also tried that. You definitely need to do that.
You need to quote the call arguments:
call getDataFor('de', 'B000lNHB8A', 2)
^--^ ^----------^
Remember that any "string" that's not in quotes will be interpreted as a table/field name reference, NOT the value it represents.

if condition inside a sql query

following is a part of my stored proceedure im using it to extract data from my db.
query
BEGIN
SET #sqlstring = CONCAT("SELECT b.ID, c.name, c.accountID,, b.total_logs, a.time_start, a.time_end ,COUNT(a.id) AS number_of_users
FROM ",logtable," a INNER JOIN users b on a.ID = b.ID INNER JOIN accounts c on b.accountID = c.accountID
GROUP BY ID;");
PREPARE stmt FROM #sqlstring;
EXECUTE stmt;
END
At times in the db, the logtable(table is passed in a variable like logtable_1, logtable_2 .... ) can be non existent, currently when the perticuler table is missing it crashes and throws an error because a.time_start, a.time_end cannot have values without the log table.
but what i want is just to assign NULL on values a.time_start, a.time_end without throwing an error,
So can any body tell is there a way i could modify this code like
BEGIN
if logtable exists
\\ the query
else
\\ the query
END
Find existence of the table by querying information_schema.tables. If it returns a count equals to 1 then you can proceed executing your query on the table. Otherwise go with your Else block.
Sample:
declare table_exists int default 0;
select count(1) into table_exists
from information_schema.tables
where table_schema='your_table_schema_name'
and table_name = 'your_table_name';
if table_exists then
-- do something
else
-- do something else
end if;