mysql function if/else - mysql

I have a function that returns a date string. I need this because I can't use a variable in a view, but I can use a function that returns a variable that I set ahead of time...
So I got all that working, but then I decided that if that I wanted it to return the current date if no date variable was set. I thought the code below wold work, but I get syntax errors...
DELIMITER $$
USE `cc`$$
DROP FUNCTION IF EXISTS `ox_date`$$
CREATE FUNCTION `ox_date`() RETURNS CHAR(50) CHARSET latin1
DECLARE ox VARCHAR(20)
IF #oxdate <1 THEN SET ox = CURDATE$$
ELSE SET ox = #oxdate$$
RETURN ox $$
DELIMITER ;
I tried isnull on that first if, but it wasn't any help.

I'm no expert but here are a few of things I see.
First, you've got
DELIMITER $$
and then use it in the function itself. That DELIMITER line allows you to use the semicolons within the body of the function. Otherwise the ';' would end the CREATE FUNCTION statement prematurely.
Also, the line
DECLARE ox varchar(20)
is missing a semicolon at the end.
And then you're missing the
END IF;
after the else condition.
Also what about the BEGIN END$$ wrapped around the function's definition?
I'd expect a stored function to generally take the form:
DELIMITER $$
DROP FUNCTION IF EXISTS `testdb`.MyFunc$$
CREATE FUNCTION `testdb`.`MyFunc` () RETURNS INT
BEGIN
DECLARE someVar varchar(20);
# some stuff
RETURN something;
END $$
DELIMITER ;
Modifying the guts of the function to suit your needs and setting the return type as appropriate.
Anyway, I'm not an expert but that is what I see and hope that helps.

Why do you need to fiddle with the delimiter? For simple logic prefer the IF function to the IF statement.
CREATE FUNCTION `ox_date`( )
RETURNS CHAR(50) CHARSET latin1
RETURN IF(#oxdate < 1 OR #oxdate IS NULL, CURDATE(),#oxdate)
Else
DELIMITER $$
USE `cc`$$
DROP FUNCTION IF EXISTS `ox_date`$$
CREATE FUNCTION `ox_date`( )
RETURNS CHAR(50) CHARSET latin1
RETURN IF(#oxdate < 1 OR #oxdate IS NULL, CURDATE(),#oxdate)$$
DELIMITER ;

Related

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.

How to make use of variable on a function

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.

MySQL Stored Procedure returns null

I did go through the similar questions and their answers of SO but it didn't help.
Here is my procedure:
DELIMITER //
DROP PROCEDURE IF EXISTS test//
CREATE PROCEDURE test()
BEGIN
DECLARE intime TIME;
SET intime:=(SELECT intime FROM new_attendance WHERE empid='xxx' AND DATE(dt)='2013-08-02');
SELECT intime;
END //
DELIMITER ;
When I execute this line of code it works and returns proper value:
SELECT empid FROM new_attendance WHERE empid='xxx' AND DATE(dt)='2013-08-02'
but it's not working inside procedure. i appreciate your help. Thanks a lot in advance!
First of all, variable assignment in MySQL takes a = syntax, not a := one.
EDIT: Strike the above, it seems that both syntaxes are supported after all...
Second, wouldn't be simpler to eliminate the intime variable altogether and just do
DELIMITER //
DROP PROCEDURE IF EXISTS test//
CREATE PROCEDURE test()
BEGIN
SELECT intime FROM new_attendance WHERE empid='xxx' AND DATE(dt)='2013-08-02';
END //
DELIMITER ;

Syntax error when importing MySQL function

I get a #1064 syntax error on the beginning of line 5's if clause when trying to run the following code in PhpMyAdmin:
DELIMITER ;
CREATE DEFINER=`root`#`localhost` FUNCTION `ANREDE`(geschlecht enum('m','w'), vorname VARCHAR(255), nachname VARCHAR(255)) RETURNS varchar(1023) CHARSET latin1
DETERMINISTIC
BEGIN
IF geschlecht = 'm' THEN RETURN CONCAT_WS('',CONCAT_WS(' ','Sehr geehrter Herr',vorname,nachname),',');
ELSE RETURN CONCAT_WS('',CONCAT_WS(' ','Sehr geehrte Frau',vorname,nachname),',');
END IF;
END
It seems to me the if clause is correct - what could cause such an error?
You can either use DELIMITER or you can rewrite your function to make it one-statement function like so
CREATE FUNCTION `ANREDE`
(
geschlecht enum('m','w'),
vorname VARCHAR(255),
nachname VARCHAR(255)
)
RETURNS VARCHAR(1023) CHARSET latin1
DETERMINISTIC
RETURN CONCAT
(CONCAT_WS(' ',
IF(geschlecht = 'm',
'Sehr geehrter Herr',
'Sehr geehrte Frau'),
vorname,
nachname),
',');
Here is SQLFiddle demo.
You need to change your delimiter. Currently, ; is your delimiter, and the parser interprets your ;, at the end of line 5, as the end of your function creation statement.
Try this:
DELIMITER // -- change the delimiter
CREATE ...
BEGIN
IF ... ; -- this is not the end of the statement
...
END
// -- end of statement
DELIMITER ; -- useless if you issue this in PhpMyAdmin, but a good practice nevertheless

Needed help to converting mssql functions into mysql

Could anyone help me to solve issues with converting MsSQL to MySQL? It gives a syntax error.
Original Mssql function:
CREATE FUNCTION StrToNum (srt1 varchar(250))
RETURNS real AS
BEGIN
DECLARE t real
IF srt1 IS NOT NULL and ISNUMERIC(srt1)=1 and PATINDEX('%,%',srt1)=0 and
PATINDEX('%e%',srt1)=0
SET t=CONVERT(Money,srt1)
ELSE
SET t=NULL
RETURN t
END
i tried like this as mysql
DELIMITER $$
CREATE FUNCTION StrToNum (srt1 VARCHAR(250))
RETURNS REAL DETERMINISTIC
BEGIN
DECLARE t REAL;
IF srt1 IS NOT NULL AND srt1 > 0 AND POSITION('%,%' IN srt1=0) AND POSITION('%e%' IN srt1=0)
THEN SET t=CONVERT(Money,INT);
ELSE
THEN SET t=NULL; END IF;
RETURN t;
END IF;
END $$
DELIMITER;
This code should parse:
DELIMITER $$
CREATE FUNCTION StrToNum (srt1 VARCHAR(250))
RETURNS REAL DETERMINISTIC
BEGIN
DECLARE t REAL;
IF srt1 IS NOT NULL AND srt1 > 0
AND POSITION('%,%' IN srt1=0)
AND POSITION('%e%' IN srt1=0)
THEN SET t=CONVERT(srt1,signed); --(1)
ELSE
SET t=NULL; END IF; --(2)
RETURN t;
END $$ --(3)
DELIMITER ; --(4)
I'll break it down for you:
CONVERT() takes SIGNED or UNSIGNED as target types. INT doesn't work. (1)
You brought forward a error from your CONVERT() syntax in mssql; you used Money instead of srt1 (1). The reason for the confusion is that CONVERT() in MSSQL and MySQL have their parameters reversed.
ELSE doesn't need (or accept) a THEN keyword after it (2)
You had an extra END IF before the final END$$ (3)
DELIMITER ; requires a space (4)