Calling a stored procedure within an IF statement MySQL - mysql

Does anybody know if this is allowed?
IF CALL GET_RIGHT_NODE(edge) = 15
THEN
SELECT "IT WORKS";
I'm getting an error on this syntax, is it possible any other way?

The return values from stored procedures should be captured in OUT paramters (whereas those from user defined functions can be captured as #returnValue = function()).
So, your GET_RIGHT_NODE should take an OUT parameter and set it to the return value.
CREATE PROCEDURE GET_RIGHT_NODE
(
#edge INT,
#returnValue INT OUTPUT
)
AS
-- Definition of the proc.
then you would call the procedure as follows:
DECLARE #returnValue INT
CALL GET_RIGHT_NODE(#edge, #returnValue)
IF (#returnValue = 15)
THEN
SELECT 'IT WORKS'

Related

I Getting error when run this below query : RETURN statements in scalar valued functions must include an argument

I am getting this error message
RETURN statements in scalar valued functions must include an argument
when run this query:
create function gender(#gender nvarchar(40))
returns nvarchar(40)
as
begin
(select name,cast(DOB as date) as DOB from datenames where gender = #gender)
return
end
The write way to create a function in mysql for your example is as follows:
DELIMITER \\
create function gender(Igender nvarchar(40))
returns nvarchar(40)
begin
DECLARE customerLevel NVARCHAR(40);
IF EXISTS (select name,cast(DOB as date) as DOB from datenames where gender = Igender) THEN
SET customerLevel = 'SOMETHING1';
ELSE
SET customerLevel = 'SOMETHING2';
END IF;
RETURN (customerLevel);
end
No need to as
No need to # before input
You need to return something.
Don't forget to use DELIMITER.
If you use phpmyadmin and has problem with nvarchar read this post: Unrecognize data type nvarchar in database or simply change it to to varchar.

Stored function in MYSQL

If I have a TABLE named MyTable which has columns say C1(type date) and C2 (type character) I want to create a stored function that takes an input and the input should always belong to C1, and the output of the stored function should be the corresponding element in C2. I have tried to do it using the 'select' statement followed by 'where' clause inside the stored function but was not able to achieve it. Is there any other way to accomplish this task.
DELIMITER $$
CREATE FUNCTION `MyFunction`
(`Date` datetime)
RETURNS char(10)
BEGIN
DECLARE MyVariable char(10)
SELECT MyVariable = `C2`
FROM MyTable
WHERE `Date` = `C1`; RETURN MyVariable;
END$$
DELIMITER ;
But this keeps giving me ERROR CODE: 1064
At first glance, I see a syntax error:
...
BEGIN
DECLARE MyVariable char(10) <-- needs a semicolon here
SELECT MyVariable = `C2`
...
Every statement within the body of your routine must end with a semicolon. See examples of DECLARE in this manual page: https://dev.mysql.com/doc/refman/8.0/en/local-variable-scope.html
It should be like this:
...
BEGIN
DECLARE MyVariable char(10);
SELECT MyVariable = `C2`
...
Re your comment:
Error 1415 means "cannot return a result set". Your stored function is doing a SELECT without putting the result into your declared local variable using an INTO keyword.
You appear to be trying to set the value of MyVariable using = but that's just making a comparison. It doesn't assign anything to MyVariable.
Without using INTO to assign the variable, your SELECT statement is by default returning a result set. This is allowed in a stored procedure, but not in a stored function. A stored function must return a single scalar value, not a result set.
...
BEGIN
DECLARE MyVariable char(10);
SELECT `C2` INTO MyVariable
FROM MyTable
WHERE `Date` = `C1`;
RETURN MyVariable;
END
P.S.: I edited your question to replace the term "user-defined function" with "stored function". These are two different things in MySQL. You are writing a stored function.
In MySQL, they use the term user-defined function (UDF) for a function you implement in C/C++ code and compile into the MySQL server. It's less common for developers to write this type of extension.

MySQL Stored procedure returning all results ignoring WHERE claus

I have two stored procs which i call from my laravel application.
My laravel application passes in a cID parameter which is then passed to the stored procedure as the "where clause". But it seems something is going astray and possibly my variables arent set up properly.
Also i know that laravel IS passing the correct cID to my stored proc because i enabled the logs for mysql to see if it was passing any params.
Also the stored procedure select statement runs fine as a query if i manually set the ClientID = '';
My stored proc sends ALL clients and cards to the view, totally ignoring the where clause.
Laravel code:
Route::get('/clients/{cID}', function ($cID) {
$details = DB::select('CALL sp_Details(' . DB::raw($cID) . ')');
$cards = DB::select('CALL sp_Cards(' . DB::raw($cID) . ')');
return view('client.show', compact('details','cards'));
});
Any my Stored Proc
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_Details`(IN cID int )
BEGIN
SET #ClientID = cID;
SELECT
ClientID,
Client_Name
FROM accounts
where #ClientID = cID;
END
Stored Proc #2
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_Cards`(cID int)
BEGIN
SET #ClientID = cID;
SELECT
ClientID,
Code
FROM cards
where cID = #ClientID;
END
You are using local variables like #ClientID and you are confusing it to column names, must change your code to avoid them and there is no necessary use the local variable:
CREATE PROCEDURE `sp_Details`(IN cID int )
BEGIN
SELECT
ClientID,
Client_Name
FROM accounts
where ClientID = cID;
END
The other proc:
CREATE PROCEDURE `sp_Cards`(cID int)
BEGIN
SELECT
ClientID,
Code
FROM cards
where ClientID = cID;
END

MySql syntax error on procedure parameter

I am trying to write a simple procedure but am encountering a syntax error at the first parameter. As best I can tell I'm following the syntax of CREATE PROCEDURE correctly.
I am limited to accessing my database with phpMyAdmin. Here is the create script I'm trying to run:
DROP PROCEDURE IF EXISTS product_index_swap/
CREATE PROCEDURE product_index_swap (#id INT, #oldIndex INT, #newIndex INT)
BEGIN
DECLARE #swapID;
SET #swapID = (SELECT `id` FROM `product` WHERE `order_index` = #newIndex LIMIT 1);
UPDATE `products` SET `order_index` = (CASE WHEN `id` = #id THEN #newIndex
WHEN `id` = #swapID THEN #oldIndex END)
WHERE `id` IN (#id, #swapID);
END
I am using the option on phpMyAdmin to change the delimiter to /.
I receive a syntax error "near '#id INT, #oldIndex INT....". I thought I may encounter more delimiter errors since I'm not entirely clear on the scope of them. I believe if that was the problem the error would be on a new line in the procedure when it failed to understand a semicolon, not at the parameters declaration.
You're using the Microsoft SQL Server convention of putting # before all the parameters and local variables. MySQL doesn't do this.
In MySQL syntax, procedure parameters have no sigil.
Also parameters are typically declared IN or OUT or INOUT.
CREATE PROCEDURE product_index_swap (IN id INT, IN oldIndex INT, IN newIndex INT)
BEGIN
DECLARE swapID;
...
MySQL variables that have the # sigil are session variables.
See also:
https://dev.mysql.com/doc/refman/5.7/en/create-procedure.html
https://dev.mysql.com/doc/refman/5.7/en/declare-local-variable.html
https://dev.mysql.com/doc/refman/5.7/en/set-variable.html
In MySQL, the #var variables are session level variables.
Use normal variables without the # and make sure you do not have conflict with column names:
CREATE PROCEDURE product_index_swap (in_id INT, in_oldIndex INT, in_newIndex INT)
BEGIN
DECLARE v_swapID int;
SELECT id into v_swapID
FROM product
WHERE order_index = in_newIndex
LIMIT 1;
UPDATE products
SET order_index = CASE WHEN id = in_id THEN in_newIndex
WHEN id = v_swapID THEN in_oldIndex
END
WHERE id IN (in_id, v_swapID);
END

Stored Procedure Return nvarchar

I have the same code below:
CREATE PROCEDURE TEST1
(#id INT, #name NVARCHAR(30) OUTPUT)
AS
SELECT #name = NAME
FROM TEACHER
WHERE ID = #id;
AND
CREATE PROCEDURE TEST2(#id INT)
AS
DECLARE #name NVARCHAR(30);
SELECT #name = NAME
FROM TEACHER
WHERE ID = #id;
RETURN #name;
The top code is OK, but the second I get an error :
Msg 245, Level 16, State 1, Procedure TEST2, Line 174
Conversion failed when converting the nvarchar value 'Nguyễn Thanh Tùng' to data type int.
Can you help me explain and fix it ??
You cannot return a varchar from a SQL Server stored procedure using RETURN - you can only return integer values.
See the MSDN documentation on "Returning Data Using a Return Code" which clearly states:
A procedure can return an integer value called a return code to indicate the execution status of a procedure.
Typically, such a value is used to either indicate the number of rows affected by your stored procedure, or to indicate an error code.
If you need to return a string, you have to use either an OUTPUT parameter, or return a result set (using a SELECT statement).