I have a mysql table of employees with columns surname and workhours for each employee . I am trying to create a stored function that takes a letter as input and returns the sum of workhours of all employees whose surname starts from the input letter .This is basically an easy task but I am a complete beginner in sql and I need your help .
What I tried :
CREATE FUNCTION sumOfTotalSickHours(letter CHAR(1))
RETURNS DOUBLE DETERMINISTIC
BEGIN
DECLARE total DOUBLE DEFAULT 0
SELECT SUM(sickleavehours) INTO total
FROM employee where lastName LIKE '#letter%'
RETURN total
END
With my above code I get a syntax error since I do not know how to write the query correctly .
First of all, each statement needs to end with a semicolon (;).
Be sure you read https://dev.mysql.com/doc/refman/8.0/en/stored-programs-defining.html to understand how to use DELIMITER when defining stored programs.
Also to reference an input variable, don't put inside quotes.
And don't use #letter because variables with the # sigil are not the same variable as without the sigil.
So for example:
CREATE FUNCTION sumOfTotalSickHours(letter CHAR(1))
RETURNS DOUBLE DETERMINISTIC
BEGIN
DECLARE total DOUBLE DEFAULT 0;
SELECT SUM(sickleavehours) INTO total
FROM employee where lastName LIKE CONCAT(letter, '%');
RETURN total;
END
Related
I have a mysql table of employees with columns surname and workhours for each employee . I am trying to create a stored function that takes a letter as input and returns the sum of workhours of all employees whose surname starts from the input letter .This is basically an easy task but I am a complete beginner in sql and I need your help .
What I tried :
CREATE FUNCTION sumOfTotalSickHours(letter CHAR(1))
RETURNS DOUBLE DETERMINISTIC
BEGIN
DECLARE total DOUBLE DEFAULT 0
SELECT SUM(sickleavehours) INTO total
FROM employee where lastName LIKE '#letter%'
RETURN total
END
With my above code I get a syntax error since I do not know how to write the query correctly .
First of all, each statement needs to end with a semicolon (;).
Be sure you read https://dev.mysql.com/doc/refman/8.0/en/stored-programs-defining.html to understand how to use DELIMITER when defining stored programs.
Also to reference an input variable, don't put inside quotes.
And don't use #letter because variables with the # sigil are not the same variable as without the sigil.
So for example:
CREATE FUNCTION sumOfTotalSickHours(letter CHAR(1))
RETURNS DOUBLE DETERMINISTIC
BEGIN
DECLARE total DOUBLE DEFAULT 0;
SELECT SUM(sickleavehours) INTO total
FROM employee where lastName LIKE CONCAT(letter, '%');
RETURN total;
END
Much appreciated if you can have a quick look on the below.
I've created the below stored function in order to format the datetime from a table to mysql format;
(%Y-%m-%d; %h:%i:%s);
Delimiter $$
create function formatdata(dataparameter varchar(20), hourparametru
varchar(20))
begin
DECLARE x time;
declare y date;
set x = (select STR_TO_DATE(Datăcolumn,'%h:%i:%s')from tabelname);
set y = (select STR_TO_DATE(oracolumn,'%Y-%m-%d')from tabelname);
select x,y;
if current_time > time(hourcolumn) then
select STR_TO_DATE(Datăcolumn,'%Y-%m-%d')into x from tabelname;
select STR_TO_DATE(oracolumn,'%h:%i:%s') into y from tabelname;
return(x,y);
end if;
end $$
Delimiter ;
What am I doing wrong here?
The error is You have an error in your sql syntax near first select_Str_to_date.
but I am kind of confused how local variables, IN parameters work together - so I am assuming that here is where I do wrong..
If you set a variable to a result of a scalar SELECT query, you put the query inside parentheses.
This:
set x = select STR_TO_DATE('07:47:20','%h:%i:%s');
Should be:
set x = (select STR_TO_DATE('07:47:20','%h:%i:%s'));
That explains the syntax error.
You also have a few other problems in this function.
Re your comment:
The line:
select x,y;
Would return a result set, but that's not allowed in a stored function (it is allowed in a stored procedure). I think you can just remove this line.
A stored function can only return a single scalar value. You should have a line RETURNS <datatype> before your BEGIN, and you should RETURN a single value somewhere in your function.
Another problem: your assignments are not valid if the table has more than one row. Setting a variable to a scalar SELECT query result is valid only if the query returns a single column and single row.
Another problem:
if current_time > time(hourcolumn) then
What is hourcolumn? It's not a function parameter or a local variable. But if it is a column of a table, there's no syntax to say which table you mean.
Another problem:
return(x,y);
You can't return a pair of variables from a stored function. Only one variable.
Another problem: The only RETURN is inside an IF block. What should the function return if the IF condition isn't true?
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