How to make use of variable on a function - mysql

I need to make a stored function:
This is my code
SELECT count(Dominio) FROM Thogar WHERE DOMINIO='%'
I need to make a stored function where I will write a letter between (U,C,R) and the function will replace the % in the previous code with the selected letter.
How can I do it? Thanks!
Got it working
CREATE FUNCTION `Buscar`(`param` CHAR(1))
RETURNS INT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE res INT;
SELECT count(Dominio) INTO res FROM Thogar WHERE DOMINIO=param;
RETURN res;
END
Call buscar('C')

This should work:
DROP FUNCTION IF EXISTS myFunc;
DELIMITER $$
CREATE FUNCTION myFunc(
param CHAR(1)
) RETURNS INT;
BEGIN
DECLARE res INT;
SELECT count(Dominio) INTO res FROM Thogar WHERE DOMINIO=param;
RETURN res;
END;
$$
DELIMITER ;

If You want to make stored function with only one sql query,
I don't see any normal reason for it.
It will not give You performance gain.
How about simplification?
You can create view:
CREATE VIEW v_dominio_counters AS
SELECT Dominio, count(Dominio) AS counter FROM Thogar GROUP BY Dominio
And then use it:
SELECT counter FROM v_dominio_counters WHERE Dominio = 'U' LIMIT 1;
It will always keep for You ready to use counters that is handy when You have huge table.

Related

SQL stored procedure- where am I going wrong?

I'm trying to create a stored procedure that calculates total revenue from a customer by if it's occupied and the standard rate. I am getting an error message and when I try to call from it I get NULL. Can anyone help? Thanks.
//Delimiter
CREATE PROCEDURE calculateRevenue (in customerIDs int, OUT totalRevenue dec(15,2))
BEGIN
SELECT SUM(Occupied*StandardRate) into totalRevenue FROM climatesouth
WHERE customerIDs = customerID;
END //
delimiter//
call calculateTotal(10, #totalRevenue);
SELECT #totalRevenue;
First you need to give your input parameters different names from the columns. Then you need to use them. Also, DELIMITER goes before the stored procedure definition:
DELIMITER //
CREATE PROCEDURE calculateRevenue (
in in_customerIDs int,
out out_totalRevenue dec(15,2))
BEGIN
SELECT SUM(cs.Occupied cs.* cs.StandardRate) into out_totalRevenue
FROM climatesouth cs
WHERE cs.customerID = in_customerID;
END //
The delimiter assignment is off: your are setting it to // after the create procedure statement.
Also, the parameter name needs to be fixed: your are not using the correct name in the query (your parameter has a trailing 's'), because of which the procedure will not produce the result you expect.
So:
delimiter // -- change the default delimiter here
create procedure calculaterevenue (in p_customerid int, out p_totalrevenue dec(15,2))
begin
select sum(occupied * standardrate) into p_totalrevenue
from climatesouth
where customerid = p_customerid; -- "p_customerid" is the parameter name
end //
delimiter ; -- reset the delimiter, now we can call the procedure
call calculaterevenue(10, #totalrevenue);
select #totalrevenue;
It is easier just to return the result as a result set rather than to use the OUT-parameter. The OUT-parameters are usually used only when calling procedure from another procedure. If you call the procedure from your application, use the result set.
delimiter //
CREATE PROCEDURE calculateRevenue (in_customerID int)
BEGIN
SELECT SUM(Occupied*StandardRate) as totalrevenue
FROM climatesouth
WHERE customerID = in_customerID;
END
//
delimiter ;
call calculateRevenue(10);

error trying to make function for counting friends

Error: There was an error while applying the SQL script to the database.
code:
USE `my_first_db`;
DROP function IF EXISTS `show_users_firends_count`;
DELIMITER $$
USE `my_first_db`$$
CREATE FUNCTION `show_users_firends_count` (ff int)
RETURNS int(11)
BEGIN
Select
count(user_friend.user_id + user_friend.friend_id)
From
user_friend
Where
user_friend.user_id = ff;
END$$
DELIMITER ;
You had it almost right.
A functions ahs to return something so you send the count back.
You should check the query anyway. your count doesn't look right. because you add useid and freind_id and count that, that is wrong. so check the query and change it. it now count all friends_id that are connected to a user_id
DROP function IF EXISTS `show_users_friends_count`;
DELIMITER $$
CREATE FUNCTION `show_users_friends_count` (ff int)
RETURNS int
DETERMINISTIC
BEGIN
Select
count(user_friend.friend_id) INTO #count
From
user_friend
Where
user_friend.user_id = ff;
RETURN #count;
END$$
DELIMITER ;

Create function that returns a "SELECT" statement result

I was told to create a mysql function that, given the artwork title, return the name of the creator. I know it sounds silly, i could use just a select.
I followed some tutorials, but none of them helped me. When I try to create the function, mysql workbench says "Error Code: 1415. Not allowed to return a result set from a function"
Here is what i'm trying to do
delimiter $$
create function findObject(workName VARCHAR(45)) returns VARCHAR(250)
begin
SELECT result= ar.artistName FROM artist as ar, art_object as oa
where ar.artistCode= oa.artistCode
and oa.title= workName
group by ar.artistName ;
return result;
end$$
delimiter ;
That's not how you assign the result of a variable in a SELECT statement. You have to use SELECT ... INTO variable.
You also need to declare the variable first.
delimiter $$
create function findObject(workName VARCHAR(45)) returns VARCHAR(250)
begin
DECLARE result VARCHAR(250);
SELECT DISTINCT ar.artistName FROM artist as ar, art_object as oa
INTO result
where ar.artistCode= oa.artistCode
and oa.title= workName;
return result;
end$$
delimiter ;
SELECT result = ar.artistName is comparing the value of result with ar.artistName, and returning the result of that comparison from the SELECT statement.

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 ;

MySQL procedure to PostgreSQL function

Migrating from MySQL to PostgreSQL.
DROP PROCEDURE IF EXISTS prepend;
DELIMITER $$
CREATE PROCEDURE prepend
(
IN inParam VARCHAR(255),
INOUT inOutParam INT
)
BEGIN
DECLARE z INT;
SET z = inOutParam + 1;
SET inOutParam = z;
SELECT inParam;
SELECT CONCAT('zyxw', inParam);
END;$$
DELIMITER ;
CALL prepend('abcdefg', #inOutParam);
The MySQL procedure call output is:
abcdefg
zyxwabcdefg
Verify the output here.
Here's the original MySQL code snippet.
The corresponding PostgreSQL function is not working. Please help.
DROP FUNCTION prepend;
CREATE OR REPLACE FUNCTION prepend
(
inParam VARCHAR,
INOUT inOutParam INT
)
AS $$
DECLARE z INT;
BEGIN
z := inOutParam + 1;
inOutParam := z;
SELECT inParam;
SELECT CONCAT('zyxw', inParam);
END; $$
LANGUAGE plpgsql;
SELECT prepend('abcdefg', 0);
PostgreSQL has not unbound queries - this technique is available on Sybase like databases (Sybase, MSSQL) and MySQL (MariaDB). Currently you can write function that can returns set of some values (tabular result) or returns scalar, composite or array (usual functions).
So most near design to your procedure is:
CREATE OR REPLACE FUNCTION prepend(inparam text)
RETURNS SETOF text AS $$
BEGIN
RETURN NEXT inparam;
RETURN NEXT 'zyxw' || inparam;
END;
$$ LANGUAGE plpgsql;
you can call this function with SELECT
SELECT * FROM prepend('abcdefg');
That is all what is possible. You cannot to set other out variables in this case.
This is common problem when you porting stored procedures from Sybase like systems that uses this technique to any other database (Postgres, Oracle, DB2, ...). The functionality of these systems cannot be mapped simply 1:1.
Because Postgres (plpgsql) has not unbounded queries support, then the syntax is prohibited.
BEGIN
SELECT 1;
END;
Has not sense there. Any result of plpgsql functions can be realized by using OUT variables or by using RETURN statement.