Creating MySQL function using date - mysql

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 ;

Related

How do I make this procedure generate random times (HH:MM:SS) but with the current date?

I need this procedure to generate 10M random timestamps but it has to use the current date each time it is called, how do i do this? I know that there's a CURRENT_TIMESTAMP() function, but I'm not sure how to implement it.
DELIMITER $$
CREATE PROCEDURE producer()
BEGIN
DECLARE a INT DEFAULT 0;
WHILE a < 10000000 DO
INSERT INTO CaseLog (`TIMESTAMP_IN`)
VALUES (FROM_UNIXTIME(UNIX_TIMESTAMP('2021-09-22 00:00:00')+FLOOR(RAND()*86399))
);
SET a = a+1;
END WHILE;
END$$
DELIMITER ;
Use CURRENT_DATE() to get today's date, and use that instead of the hard-coded date.
DELIMITER $$
CREATE PROCEDURE producer()
BEGIN
DECLARE today_timestamp INT;
SET today_timestamp = UNIX_TIMESTAMP(CURRENT_DATE());
DECLARE a INT DEFAULT 0;
WHILE a < 10000000 DO
INSERT INTO CaseLog (`TIMESTAMP_IN`)
VALUES (FROM_UNIXTIME(today_timestamp+FLOOR(RAND()*86400)));
SET a = a+1;
END WHILE;
END$$
DELIMITER ;
Also, you should multiply RAND() by 86400, not 86399. The result of RAND() is always less than 1.0, so you don't have to worry that it will return 86400.

'While' loop is not exiting after set number of seconds

The goal here is to make it busy for 'n' seconds and then exit.
This is latest version of code. I tried direct date1 < date2 in while, etc
delimiter $$
CREATE FUNCTION `DelayResponse`(pSeconds int) RETURNS varchar(1)
BEGIN
DECLARE x int;
DECLARE EndDateTime datetime ;
DECLARE CurrDateTime datetime ;
Set x = 0;
set EndDateTime = DATE_ADD(now(), INTERVAL pSeconds second);
set CurrDateTime = now();
WHILE x = 0 DO
-- expecting to set x to 1 in pSeconds but nope
if CurrDateTime > EndDateTime then
set x = 1;
end if;
SET CurrDateTime = now();
END WHILE;
RETURN 'X';
END$$
delimiter ;
select DelayResponse(5) X
I can't get out the loop here. What am I missing?
Another version that does not work. Just spins running... not ending
delimiter $$
CREATE FUNCTION `DelayResponse`(pSeconds int) RETURNS varchar(1)
BEGIN
DECLARE x int;
DECLARE EndDateTime datetime ;
Set x = 0;
set EndDateTime = DATE_ADD(now(), INTERVAL pSeconds second);
WHILE x <= 0 DO
set x = now() - EndDateTime;
END WHILE;
RETURN 'X';
END$$
delimiter ;
This behaviour is a result of a documented, but less-known feature of now(). So, this is not a bug!
NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes.
So, while #Barmar is correct in suggesting the use of sleep(), you can make your original code work with sysdate() instead of now().
You can use the built-in SLEEP() function instead of your own loop.
delimiter $$
CREATE FUNCTION `DelayResponse`(pSeconds int) RETURNS varchar(1)
BEGIN
DO SLEEP(pSeconds);
RETURN 'X';
END$$
delimiter ;
select DelayResponse(5) X

MySQL ERROR #1415 - Not allowed to return a result set from a function

My question is about a function returning only one value but I still get this error, so What I'm supposed to get is average day between the order date and the shipped date, the query is doing that and returning me only one value which is the average. If I use just the SELECT statement outside the of the function I get one column/row answer of 8.4920.
How can I fix that please. Thanks.
DELIMITER //
DROP FUNCTION IF EXISTS OrderFulfilmel//
CREATE FUNCTION OrderFulfilmel(average int) RETURNS DOUBLE Deterministic
BEGIN
SELECT AVG(DATEDIFF(ShippedDate, OrderDate)) AS averageDay
FROM Orders;
END//
DELIMITER ;
You can try below
CREATE FUNCTION OrderFulfilmel(average int) RETURNS DOUBLE Deterministic
BEGIN
DECLARE var_name DECIMAL(10,2);
SET var_name = 0;
SELECT AVG(DATEDIFF(ShippedDate, OrderDate)) INTO var_name
FROM Orders;
RETURN var_name;
END
I don't understand why your function would have an argument. So, I'm thinking:
DELIMITER //
DROP FUNCTION IF EXISTS OrderFulfilmel//
CREATE FUNCTION OrderFulfilmel ()
RETURNS DOUBLE Deterministic
BEGIN
DECLARE #diff DOUBLE;
SELECT #diff := AVG(DATEDIFF(ShippedDate, OrderDate)) AS averageDay
FROM Orders;
RETURN #diff;
END//
DELIMITER ;

my function is returning nothing

DELIMITER //
DROP FUNCTION IF EXISTS TotalProductionCost;
CREATE FUNCTION TotalProductionCost(Abuilt int(10),Ucost Decimal(5,2) )
RETURNS Decimal(5,2)
BEGIN
DECLARE TotalCost Decimal(5,2);
SET TotalCost = Abuilt * Ucost;
RETURN TotalCost;
END //
DELIMITER ;
SELECT TotalProductionCost(10,1000) AS TotalCost;
I have created above function when Execute it in mysql workbench it worked fine query executed,but when I called function,it didnt return anything.. query executed suceefully.
The sizing of your decimal is exploding based on your input and output of (5,2).
The following works:
DROP FUNCTION IF EXISTS TotalProductionCost;
DELIMITER $$
CREATE FUNCTION TotalProductionCost(Abuilt int,Ucost DECIMAL(12,2) )
RETURNS Decimal(12,2)
DETERMINISTIC
BEGIN
DECLARE TotalCost Decimal(12,2);
SET TotalCost = Abuilt * Ucost;
RETURN (TotalCost);
END $$
DELIMITER ;
test:
SELECT TotalProductionCost(10,1000.12) AS TotalCost;
So, yes, I confirmed yours choked. And you need to be careful with your sizing for the in and return.

MYSQL stored procedure if else dayname

I need to Write a stored procedure to find out the joining date of teachers and if it is a Monday it should display Monday else it should display Weekday. I am very new in stored procedure how i can display 'weekday?
I have prepared a code but am geting error.(dat_teacher_doj is in date datatype)
Delimiter //
CREATE PROCEDURE check_date(IN doj date)
BEGIN
select dayname(dat_teacher_doj)as day from tbl_teachers where dat_teacher_doj=doj;
IF day!='Monday' THEN
SET day='Weekday';
END IF
END //
Delimiter ;
AM GETTING ERROR: UNKNWN SYSTEM VARIABLE 'day'
You first need to DECLARE your variable. Then use SELECT ... INTO after you have declared your variable.
DELIMITER //
CREATE PROCEDURE check_date (IN teacher_id VARCHAR(100))
BEGIN
DECLARE day VARCHAR(100);
SELECT dayname(dat_teacher_doj) INTO day FROM tbl_teachers WHERE id = teacher_id;
SELECT CASE WHEN day != 'Monday' THEN 'Weekday' ELSE day END;
END;
//
DELIMITER ;
When you call your procedure, you need to put quotes around your input date.
call check_date('1982-01-11');