User Defined Function MySQL Workbench - mysql

How do I execute a user defined function so that the database will recognize that the function has been created?
DELIMITER $$
CREATE FUNCTION `StudentGPA` (StudentID int, ClassStartDateStart datetime, ClassStartDateEnd date time) RETURNS decimal(3,2)
BEGIN
Declare AvgGPA decimal(3,2);
SELECT AvgGPA= isNULL(Avg(GPA), 0.0)
FROM Students_Classes
WHERE StudentID = StudentID
AND StartDate > ClassStartDateStart
AND StartDate <= ClassStartDateEnd
AND GPA > 0; RETURN AvgGPA;
END

When running your code, you should get a syntax error. In your CREATE statement where you're specifying your parameters you need to change ClassStartDateEnd date time to ClassStartDateEnd datetime.
DELIMITER $$
CREATE FUNCTION `StudentGPA`
(StudentID int,
ClassStartDateStart datetime,
ClassStartDateEnd datetime)
RETURNS decimal(3,2)
BEGIN
Declare AvgGPA decimal(3,2);
SELECT AvgGPA= isNULL(Avg(GPA), 0.0)
FROM Students_Classes
WHERE StudentID = StudentID
AND StartDate > ClassStartDateStart
AND StartDate <= ClassStartDateEnd
AND GPA > 0; RETURN AvgGPA;
END$$
DELIMITER ;
I have also used your DELIMITER of $$ after your END statement to properly terminate the CREATE, then set the delimiter back to ; which is good practice.

Related

Declaring INT variable to return in MYSQL Function problem

I'm trying to build a mysql function which inserts values into a table and returns me the last_id inserted, which should be the same after executing the insertion. But Xampp gives me an error in the line where im declaring the "last_bill_id" variable. Can someone please help me to understand what am I doing wrong?
Here is the code for the function:
CREATE FUNCTION insert_bill(
client_id varchar (12),
bill_date date
) RETURNS INT
BEGIN
DECLARE last_bill INT;
INSERT INTO bill
(
client_id, bill_date
)
VALUES
(
client_id, bill_date
);
SET last_bill = LAST_INSERT_ID();
RETURN last_bill;
END $$
DELIMITER ;
Error: #1064 - Something is wrong about 'INT
you need another DELIMITER at the start
DELiMiTER $$
CREATE FUNCTION insert_bill(
client_id varchar (12),
bill_date date
) RETURNS INT
DETERMINISTiC
BEGIN
DECLARE last_bill INT;
INSERT INTO bill
(
client_id, bill_date
)
VALUES
(
client_id, bill_date
);
SET last_bill := LAST_INSERT_ID();
RETURN last_bill;
END $$
DELIMITER ;

MySQL 5.7 create Function with int input syntax errors

Trying to create a function in MySQL 5.7 that will return the total sales for a year, formatted with a $, and two decimal places given the year as an integer input.
Table columns InvoiceID, deptid, salsamt, salesdate
DELIMITER $$
CREATE FUNCTION `tot_sale` (Year INT)
RETURNS VARCHAR2
BEGIN
Select concat('$', format(salesamt), 2)
from sales
where YEAR(salesdate) = Year;
RETURN 1;
END$$
DELIMITER ;
2 needs to be the second argument to FORMAT(), not an argument to CONCAT().
If a function uses SELECT, it has to store the result in a variable. Only procedures are allowed to return a result set directly.
You need to use SUM(salesamt) to get the total sales for the year.
DELIMITER $$
CREATE FUNCTION `tot_sale` (Year INT)
RETURNS VARCHAR(255)
BEGIN
DECLARE total VARCHAR(255);
Select concat('$', format(SUM(salesamt), 2))
INTO total
from sales
where YEAR(salesdate) = Year;
RETURN #total;
END$$
DELIMITER ;

Creating MySQL function using date

DELIMITER $$
CREATE FUNCTION current_age (birthdate date)
RETURNS date
BEGIN
DECLARE age_return date;
DECLARE rightnow date;
SET rightnow = date(now());
SET age_return = timestampdiff(year, rightnow, date(birthdate));
RETURN age_return;
END $$
DELIMITER ;
select current_age(date('2017-06-30'));
I am trying to create a function which years the difference in years. I cant get it to work and I dont understand why, because the following works fine outside the function.
SET #birthdate = '2001-01-01';
SET #rightnow = date(now());
SELECT timestampdiff(year, #rightnow, date(#birthdate))
If we want to return a number of years, then the return type would be a numeric type like INT or DECIMAL. We wouldn't return a DATE datatype.
DELIMITER $$
CREATE FUNCTION current_age(birthdate DATE)
RETURNS INT
BEGIN
RETURN TIMESTAMPDIFF(YEAR,birthdate,DATE(NOW()));
END$$
DELIMITER ;

MySQL stored procedure syntax error in variables

I have table group with begindate lesson count and weekdays columns. I would like write MySQL procedure for adding data to another table named lessons according to group. But I couldn't handle with syntax of MySQL. Could you please help me resolve problems with that procedure:
CREATE PROCEDURE simpleproc (IN idGroup INT, IN groupName varchar(20),IN beginDate date, IN weekday1 INT, IN weekday2 INT, IN lessonCount INT)
BEGIN
DECLARE i;
SET i:=1;
WHILE i<=lessonCount DO
DATE_ADD(beginDate,INTERVAL 1 DAY)
IF (WEEKDAY(beginDate)=weekday1) OR (WEEKDAY(beginDate)=weekday2) THEN
SET name:=groupName+i;
SET price:=DIV(price,8)
insert into lessons (lessonName, idGroup, lessonPrice, datePassed)
values (name,idGroup,price,begindate);
SET i:=i+1
END IF;
END WHILE;
END
After solving problems I will add this code to prepared statement in Java
This will run. Make sure: 1. That you increment i in a proper place of your code inside the while loop. 2. Avoid usind reserved words (like name) for fields and variables. 3. Define price variable somewhere before making integer division of it. You know the code and your tables' structure. Nobody is capable to do it for you.
DROP PROCEDURE IF EXISTS `simpleproc`;
DELIMITER ;;
CREATE DEFINER=`root`#`localhost` PROCEDURE `simpleproc`(IN idGroup INT, IN groupName varchar(20),IN beginDate date, IN weekday1 INT, IN weekday2 INT, IN lessonCount INT)
BEGIN
DECLARE i int;
DECLARE name1 int;
DECLARE price int;
SET i:=1;
WHILE i<=lessonCount DO
SET beginDate:=DATE_ADD(beginDate,INTERVAL 1 DAY);
IF WEEKDAY(beginDate) in(weekday1,weekday2) THEN
SET name1:=groupName+i;
SET price:=price DIV 8;
insert into lessons (lessonName, idGroup, lessonPrice, datePassed)
values (name1,idGroup,price,begindate);
END IF;
SET i:=i+1;
END WHILE;
END
;;
DELIMITER ;

Conversion ms sql function into mysql

I'm facing a problem while converting ms sql function into mysql. Here is ms sql function code:
CREATE FUNCTION [crewu2].[isAvailable] (#OwnerID int, #DateFrom Smalldatetime, #DateTo Smalldatetime)
RETURNS bit AS
BEGIN
DECLARE #t bit
IF #DateFrom IS NULL or #DateTo IS NULL
or EXISTS (select DateID
from [client_BlackDates]
where OwnerID=#OwnerID
and ((DateFrom<=#DateFrom and #DateFrom<=DateTo)
or (DateFrom<=#DateTo and #DateTo<=DateTo)))
SET #t=0
ELSE
SET #t=1
RETURN #t
END
And here is converted in mysql:
DELIMITER $$
CREATE FUNCTION isAvailable (OwnerID INT, DateFrom DATETIME, DateTo DATETIME)
RETURNS BIT
BEGIN
DECLARE t BIT;
IF DateFrom IS NULL OR DateTo IS NULL
OR EXISTS (SELECT DateID
FROM client_BlackDates
WHERE OwnerID=OwnerID
AND ((DateFrom<=DateFrom AND DateFrom<=DateTo)
OR (DateFrom<=DateTo AND DateTo<=DateTo)))
SET t=0;
ELSE
SET t=1;
RETURN t
END $$
DELIMITER;
but it gives me 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 'SET t=0;
ELSE
SET t=1;
RETURN t
END' at line 6
Please anyone help me regarding this.
This should work(You have missed THEN and END IF):
DELIMITER $$
CREATE FUNCTION isAvailable (OwnerID INT, DateFrom DATETIME, DateTo DATETIME)
RETURNS BIT
BEGIN
DECLARE t BIT;
IF DateFrom IS NULL OR DateTo IS NULL OR EXISTS (SELECT DateID FROM client_BlackDates WHERE OwnerID=OwnerID AND ((DateFrom<=DateFrom AND DateFrom<=DateTo) OR (DateFrom<=DateTo AND DateTo<=DateTo)))
**THEN**
SET t=0;
ELSE
SET t=1;
RETURN t;
**END IF;**
END $$
DELIMITER ;
Refer MySQL docs.
Take a look into MySQL manual to the IF..THEN..ELSE sintax
DELIMITER //
CREATE FUNCTION isAvailable (OwnerID INT, DateFrom DATETIME, DateTo DATETIME)
RETURNS BIT
BEGIN
DECLARE t BIT;
IF DateFrom IS NULL OR DateTo IS NULL
OR EXISTS (SELECT DateID
FROM client_BlackDates
WHERE OwnerID=OwnerID
AND ((DateFrom<=DateFrom AND DateFrom<=DateTo)
OR (DateFrom<=DateTo AND DateTo<=DateTo)))
THEN
SET t = 0;
ELSE
SET t = 1;
END IF;
RETURN t;
END //
DELIMITER ;