i am trying to make a stored procedure that has multiple optionals parameters, i have tried with IF statement but i can't make it work and this is the last code i have tried.
I want to filter by "Usuario" if it is not null
I'm giving "Usuario" as an example, but it will have others filters like it.
CREATE DEFINER=`conciliacion`#`%` PROCEDURE `BuscarRRNormal`(IN `FechaDesde` DATE, IN `FechaHasta` DATE, IN `Usuario` varchar(255))
BEGIN
SELECT IDS, Fecha_Recarga, Usuario, Monto, Operador
FROM transaccionesrr
WHERE (Fecha_Recarga BETWEEN FechaDesde AND FechaHasta)
AND (#Usuario IS NULL OR Usuario = #Usuario);
END
It's seems like mySQL doesn't support optional parameters but there could be a similar option?. Any help will be appreciated.
In MySQL, the variable #Usario is not the same object as the procedure IN parameter Usario. They are different variables. You cannot reference #Usario to get the value of the IN parameter Usario.
You should name your parameter something distinct from the column name you want to compare it to, then just use it in the query without a # character. For example, one could use a naming convention to prefix the parameter names with "p".
CREATE DEFINER=`conciliacion`#`%` PROCEDURE `BuscarRRNormal`(IN `pFechaDesde` DATE, IN `pFechaHasta` DATE, IN `pUsuario` varchar(255))
BEGIN
SELECT IDS, Fecha_Recarga, Usuario, Monto, Operador
FROM transaccionesrr
WHERE (Fecha_Recarga BETWEEN pFechaDesde AND pFechaHasta)
AND (pUsuario IS NULL OR Usuario = pUsuario);
END
Related
I'm trying to write a stored procedure which takes in a value then compares it with a table value. For example
The procedure takes in a varchar(30) value say " RED " as c_title then compares it with all the titles in a table called campaign, if matching then update some column with a certain value.
basically how would you compare two variables of string values in mysql?
I've tried different comparison methods using LIKE, IN and =
CREATE PROCEDURE sp_finish_campaign(in c_title varchar(30))
Begin
Update campaign
Set TITLE = "Hello"
where TITLE = c_title;
END
New Title value should be hello where TITLE matches the input value
but im getting error code 1064 for syntax error.
Appreciate any feedback. Thank you
You need to end your update with a semicolon, but first redefine the delimiter which will be used by the stored procedure:
DELIMITER // ;
CREATE PROCEDURE sp_finish_campaign(IN c_title varchar(30))
BEGIN
UPDATE campaign
SET TITLE = 'Hello'
WHERE TITLE = c_title;
END //
Also, you should try to use single quotes when defining string literals in MySQL. Double quotes most likely would work also, but they are mainly used to indicate database objects (e.g. database, table, and column names), rather than strings.
I am trying to write a function that looks for a value assigned to its configuration in a parent-child tree, if the value is null or empty it looks one level up for the value.
I am currently getting syntax errors when trying to create the function.
This is what i have so far,
DELIMITER //
CREATE FUNCTION `db`.`Configuration`(
`ColumnName` VARCHAR(128),
`CID` INT
)
RETURNS VARCHAR(256)
NOT DETERMINISTIC
BEGIN
DECLARE Config VARCHAR(256) DEFAULT NULL;
DECLARE Parent INT;
WHILE (#Config IS NULL OR #Config = "") DO
SELECT #ColumnName INTO #Config, `ParentID` INTO #Parent FROM `Table` WHERE `ID`=#CID;
END WHILE;
RETURN CONCAT(#Config, '::', #Parent);
END ;
//
DELIMITER ;
I am getting the following error when I try to add the function:
1327 - Undeclared variable: ParentID
Any help would be greatly appreciated!
You receive the error message in the question because you have multiple into clauses, whereas according to mysql manual on select ... into ... you can only have one. So, to get rid of this specific error message you nee to rewrite your select statement as:
SELECT #ColumnName, `ParentID` INTO #Config, #Parent FROM `Table` WHERE `ID`=#CID;
However, there are some further issues with your code:
varname and #varname do not refer to the same variable. The first one is either a function / stored proc parameter or local variable, while the 2nd one is a user-defined variable. In your code you must remove the # from the variable names.
You cannot use a variable in place of a field name in an sql statement. You must use dynamic sql with prepared statements to achieve this. See the following SO question on how to this: How To have Dynamic SQL in MySQL Stored Procedure
You do not overwrite CID parameter in your while loop. This means that if the first iteration the configuration will remain null, then you have an infinite loop. You should change the value of CID in your loop.
I cannot guarantee that there are no further errors in your code.
There are a few problems with your function:
You are using SELECT...INTO incorrectly. When selecting multiple values you should only use INTO once. For example SELECT a,b into #a,#b FROM...
You are using user-defined variables with similar names to your function parameters, but they are not the same thing. In your code CID and #CID are different. I suggest using standard naming prefixes to clarify this: for example use p_ for function parameters and v_ for local function variables. You shouldn't need to use user-defined variables at all.
Your WHILE loop is bound to lead to infinite loops since the query criteria never changes. If it returns NULL or empty string once, it will keep returning them forever.
Here's a quick rewrite to address the above issues. I'll leave it to you to implement the WHILE loop correctly:
DELIMITER //
CREATE FUNCTION `db`.`Configuration`(
p_column_name VARCHAR(128),
p_id INT
)
RETURNS VARCHAR(256)
READS SQL DATA
BEGIN
DECLARE v_config VARCHAR(256) DEFAULT NULL;
DECLARE v_parent INT;
SELECT p_column_name,`ParentID`
INTO v_config, v_parent
FROM `Table`
WHERE `ID`=p_id;
RETURN CONCAT(v_config, '::', v_parent);
END ;
//
DELIMITER ;
I have created one procedure which take 2 parameter and it check the count.
But when I pass "" blank value It still return 1 count.
Did not get it why it is working like this.
Thanks for the help below is my procedure
DELIMITER $$
CREATE DEFINER=`dadclient`#`123.63.249.169` PROCEDURE `checkInOut`(IN grid varchar(50),OUT count INT)
begin
select count(GRIDID) into count from GRIDID where GRIDID=grid;
select count;
END
when I call
checkInOut("",#aaa);
select #aaa;
When I call this,it return me 1 which is wrong.
But when I pass "" blank value It still return 1 count.
Because when you say it is blank by providing an empty string it is a value. Empty string is also treated as a value in database and hence you get count as 1
The MySQL docs says:
COUNT(expr)
Returns a count of the number of non-NULL values of expr in the rows
retrieved by a SELECT statement. The result is a BIGINT value.
So if you want the count to return 0 then instead of making the string as empty "" you need to make the value as NULL.
Yo mate, try this:
DELIMITER $$
CREATE
DEFINER=`dadclient`#`123.63.249.169`
PROCEDURE `checkInOut`(
IN `grid` VARCHAR(50),
OUT `count` INT
)
BEGIN
-- insert value into variable
SET `count` = (
select count(GRIDID)
from GRIDID
where GRIDID=grid;
);
END$$
DELIMITER ;
So in your application, e.g. php you can CALL checkInOut($input, $output);. No need for the final SELECT... part in your initial code, afaik, because you already declared count as an OUT in the procedure parameter
Note:
Is the name GRIDID the name of your table? because as I see, you also used it in your WHERE statement as a key filter
Regarding your query, supposedly it is expected to contain one row of result. Kindly check that also mate
I keep getting a null value when using an out parameter.
CREATE PROCEDURE `getTotalPoints`(IN `uEmail` VARCHAR(255), OUT `iTotal` DECIMAL(5,2) UNSIGNED)
begin
select
coalesce(
coalesce(sum(points_earned),0) -
coalesce(sum(points_lost),0) +
coalesce(sum(points_taken),0) -
coalesce(sum(points_traded),0),0)
from user_activities
where user_email=#uEmail into #iTotal;
end
I know the select statement works fine as without the out parameter, I get 0.00 as a result.
I'm sure it's something simple, but everything I've researched and tried has resulted in the same NULL return value.
Remove the "#" symbols on the variable references.
"#uEmail" and "#iTotal" are references to user-defined variables, not the procedure arguments.
You want to reference the procedure arguments as "uEmail" and "iTotal", without the "#".
Or, you could probably get your statement to work if you did the necessary assignments to and from the user-defined variables, something like this in the body of the procedure:
-- set user-defined variable to value from procedure argument
SET #uEmail = uEmail;
-- statement references user-defined variables
SELECT ...#uEmail ... INTO #iTotal;
-- set procedure OUT argument from user-defined variable
SET iTotal = #iTotal;
the problem is, I have a procedure which returns a set of values and the column name returned by that procedure is friend, it accepts 1 parameter that is username,
now I have two queries:
call test('nishchal') and call test('nootan') now I want the common values returned by these two procedure, any solution guys??
My procedure has these lines of codes
begin
select u_name` as friend
from table_name
where f_id = username
end
where username is the parameter passed
It's a bit clunky but you could put the results into a temporary table.