MySQL: Procedure Loops, but only inserts once - mysql

CREATE DEFINER=`root`#`localhost` PROCEDURE `GenerateCharges2`()
BEGIN
Declare sumFunding LONG;
Declare done INT DEFAULT FALSE;
Declare invoiceCharge LONG;
Declare agencyID INT;
declare invoiceID int;
Declare fundingID INT;
Declare amountOfFunding LONG;
Declare getInvoiceData CURSOR For select invoices.idInvoices, invoices.idAgencies, invoices.InvoiceAmount, fundings.FundingBalance, fundings.idfundings from invoices
inner join agencies on invoices.idAgencies = agencies.idAgencies
inner join fundings on agencies.idAgencies = fundings.IdAgencies
where processed =0
group by invoices.idInvoices;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
open getInvoicedata;
ze_loop: Loop
Fetch getInvoiceData into invoiceID, agencyID, invoiceCharge, amountOfFunding, fundingID;
if done then leave ze_loop;
end if;
if amountOfFunding > invoiceCharge then
insert into charges VALUES (invoiceCharge, invoiceID, fundingID);
end if;
end loop;
close getInvoiceData;
END
My issue is that if you were to insert a select statement, it runs a proper amont of times. However, the insert statement only inserts once with sample data. In every case, amnountOfFunding is ALWAYS greater than invoiceCharge. Desired results is to have all inserts happen for rows fetched.

I have this loop and insert every record that i need! Maybe you can modifiy or update yours loop with that!
DECLARE done INT DEFAULT FALSE ;
DECLARE l_local_formato_retail_codigo,
l_producto_sku,
l_producto_descripcion_sra,
l_producto_marca,
l_producto_categoria VARCHAR (100) ;
DECLARE l_precio DECIMAL (20, 7) DEFAULT 0 ;
DECLARE l_un_1 INT (20) DEFAULT 0 ;
DECLARE l_un_2 INT (20) DEFAULT 0 ;
DECLARE l_clp_1 DECIMAL (20, 7) DEFAULT 0 ;
DECLARE l_clp_2 DECIMAL (20, 7) DEFAULT 0 ;
DECLARE contador INT DEFAULT 0 ;
DECLARE valores CURSOR FOR
SELECT
local_formato_retail_codigo,
producto_sku,
producto_descripcion_sra,
producto_marca,
producto_categoria
FROM
base_comercial
WHERE mes_fecha = fecha
GROUP BY producto_sku,
local_formato_retail_codigo
ORDER BY local_formato_retail_codigo ASC,
producto_sku ASC ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE ;
TRUNCATE precio_cd ;
OPEN valores ;
read_loop :
LOOP
FETCH valores INTO l_local_formato_retail_codigo,
l_producto_sku,
l_producto_descripcion_sra,
l_producto_marca,
l_producto_categoria ;
IF done
THEN LEAVE read_loop ;
END IF ;
SET l_clp_1 =
(SELECT
ROUND(SUM(sellout_clp), 7)
FROM
base_comercial
WHERE anno = DATE_FORMAT(fecha, '%Y')
AND mes = DATE_FORMAT(fecha, '%c')
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
SET l_clp_2 =
(SELECT
ROUND(SUM(sellout_clp), 7)
FROM
base_comercial
WHERE anno = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%Y'
)
AND mes = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%c'
)
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
SET l_un_1 =
(SELECT
SUM(sellout_un)
FROM
base_comercial
WHERE anno = DATE_FORMAT(fecha, '%Y')
AND mes = DATE_FORMAT(fecha, '%c')
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
SET l_un_2 =
(SELECT
SUM(sellout_un)
FROM
base_comercial
WHERE anno = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%Y'
)
AND mes = DATE_FORMAT(
DATE_ADD(fecha, INTERVAL - 1 MONTH),
'%c'
)
AND local_formato_retail_codigo = l_local_formato_retail_codigo
AND producto_sku = l_producto_sku) ;
IF (ISNULL(l_clp_1))
THEN SET l_clp_1 = 0 ;
END IF ;
IF (ISNULL(l_clp_2))
THEN SET l_clp_2 = 0 ;
END IF ;
IF (ISNULL(l_un_1))
THEN SET l_un_1 = 0 ;
END IF ;
IF (ISNULL(l_un_2))
THEN SET l_un_2 = 0 ;
END IF ;
SET l_precio = ((l_clp_1 + l_clp_2) / (l_un_1 + l_un_2)) ;
IF (ISNULL(l_precio))
THEN SET l_precio = 0 ;
END IF ;
INSERT INTO precio_cd
VALUES
(
l_local_formato_retail_codigo,
l_producto_sku,
l_producto_descripcion_sra,
l_producto_marca,
l_producto_categoria,
l_precio
) ;
END LOOP read_loop ;
CLOSE valores ;
SELECT
*
FROM
precio_cd ;

Related

How do I fetch the data using multiple cursors and multiple loops in MySQL Stored Procedure?

As per the use case, this procedure should return 30 rows with 15 unique lead id's corresponding to all 15 in activity=1; randomly 10 participate in activity = 2; and from those 10, 5 leads randomly correspond to activity=3.
When I run the stored procedure, it goes on until populating 25 records; which correspond to uniquely getting 15 id's for activity=1 and 10 out of them for activity=2; but, I am unable to fetch the records right after.
If you check down in the code; I have mentioned a SELECT statement just before closing cur2 (SELECT COUNT(*) FROM task2), which should return Count=25; but it's not. So, apparently, the program isn't even going further into the cur3 which I have declared for activity=3.
I have tried using Continue Handler with cursor, too; but it didn't seem to work!
Can anyone help resolve this issue?
BEGIN
DROP TABLE IF EXISTS task2;
CREATE TABLE task2 (
ID int(11) NOT NULL AUTO_INCREMENT,
type_id int(11) DEFAULT NULL,
url varchar(100) DEFAULT NULL,
lead_id int(11) DEFAULT NULL,
createdDate datetime DEFAULT NULL,
month varchar(20) DEFAULT NULL,
year int(11) DEFAULT NULL,
month_year varchar(20) DEFAULT NULL,
PRIMARY KEY (ID)
)
BEGIN
-- INSERTING DATA FOR ACTIVITY = 1
DECLARE nurl VARCHAR(100);
DECLARE nleadid INTEGER;
DECLARE ncreateddate DATETIME;
DECLARE l_count INTEGER;
DECLARE loop_count INTEGER;
-- LOOP COUNT = 15
SET l_count = 15;
SET loop_count = 1;
read_loop:LOOP
IF loop_count > l_count THEN
LEAVE read_loop;
END IF;
IF loop_count = 1
THEN
SET nleadid = 100;
SET ncreateddate = ('2012-09-08 01:09:30');
ELSE
SET nleadid = 100 + loop_count - 1;
SET ncreateddate = (SELECT MAX(createdDate) FROM task2);
SET ncreateddate = DATE_ADD(ncreateddate, INTERVAL ELT(0.5 + RAND() * 6, '3', '5', '45', '34', '23', '68') MINUTE);
END IF;
SET nurl = ELT(0.5 + RAND() * 3, 'g.com', 'y.com', 'm.com');
INSERT INTO task2 (type_id, url, lead_id, createdDate)
VALUES ('1', nurl, nleadid, ncreateddate);
UPDATE task2
SET month = MONTHNAME(createddate), year = YEAR(createddate), month_year = CONCAT(MONTHNAME(createddate),'-', YEAR(createddate));
SET loop_count = loop_count + 1;
END LOOP read_loop;
END;
-- INSERTING THE DATA FOR ACTIVITY = 2
BEGIN
DECLARE nurl VARCHAR(100);
DECLARE nleadid INTEGER;
DECLARE ncreateddate DATETIME;
DECLARE l_count INTEGER;
DECLARE loop_count INTEGER;
-- CURSOR DECLARATION TO FETCH 10 RANDOM RECORDS FROM ACTIVITY=1
DECLARE cur2 CURSOR FOR
SELECT DISTINCT lead_id FROM task2 WHERE type_id = 1 ORDER BY RAND() LIMIT 10;
SET l_count = 10;
SET loop_count = 1;
OPEN cur2;
read_loop:LOOP
FETCH cur2 INTO nleadid;
IF loop_count > l_count THEN
SELECT loop_count_2, l_count_2;
LEAVE read_loop;
END IF;
SET nurl = ELT(0.5 + RAND() * 3, 'g.com', 'y.com', 'm.com');
SET ncreateddate = (SELECT MAX(createdDate) FROM task2 WHERE lead_id = nleadid);
SET ncreateddate = DATE_ADD(ncreateddate, INTERVAL ELT(0.5 + RAND() * 6, '3', '5', '45', '34', '23', '68') MINUTE);
INSERT INTO task2 (type_id, url, lead_id, createdDate)
VALUES ('2', nurl, nleadid, ncreateddate);
UPDATE task2
SET month = MONTHNAME(createddate), year = YEAR(createddate), month_year = CONCAT(MONTHNAME(createddate),'-', YEAR(createddate));
SET loop_count = loop_count + 1;
SELECT COUNT(*) FROM task2;
END LOOP read_loop;
SELECT COUNT(*) FROM task2;
CLOSE cur2;
END;
-- INSERTING DATA FOR ACTIVITY = 3
BEGIN
DECLARE nurl VARCHAR(100);
DECLARE nleadid INTEGER;
DECLARE ncreateddate DATETIME;
DECLARE l_count INTEGER;
DECLARE loop_count INTEGER;
-- CURSOR DECLARATION FOR SELECTING 5 RANDOM LEADS FROM ACTIVITY=2
DECLARE cur3 CURSOR FOR
SELECT DISTINCT lead_id FROM task2 WHERE type_id = 2 ORDER BY RAND() LIMIT 5;
SET l_count = 5;
SET loop_count = 1;
OPEN cur3;
read_loop:LOOP
IF loop_count > l_count THEN
LEAVE read_loop;
END IF;
FETCH cur3 INTO nleadid;
SET nurl = CONCAT(ELT(0.5 + RAND() * 3, 'g.com', 'y.com', 'm.com'), ELT(0.5 + RAND() * 3, '/home.html', '/index.html', '/about.html'));
SELECT nurl;
SET ncreateddate = (SELECT MAX(createdDate) FROM task2 WHERE lead_id = nleadid);
SET ncreateddate = DATE_ADD(ncreateddate, INTERVAL ELT(0.5 + RAND() * 6, '3', '5', '45', '34', '23', '68') MINUTE);
SELECT ncreateddate;
INSERT INTO task2 (type_id, url, lead_id, createdDate)
VALUES ('3', nurl, nleadid, ncreateddate);
UPDATE task2
SET month = MONTHNAME(createddate), year = YEAR(createddate), month_year = CONCAT(MONTHNAME(createddate),'-',YEAR(createddate));
SET loop_count =loop_count + 1;
END LOOP read_loop;
CLOSE cur3;
END;
SELECT * FROM task2;
END

Case not working for my stored procedure

I have created this procedure to insert upc_id and relevent values in the table product_universal_description.
CREATE PROCEDURE veealpha
(
IN s_po_id INT(11),
IN s_supplier_id INT(11),
IN s_location_id VARCHAR(32),
IN s_warehouse_id INT(11),
IN s_user_id INT(11),
OUT message VARCHAR(64),
OUT error_code INT(4)
)
BEGIN
DECLARE temp_upc VARCHAR(32);
DECLARE i INT;
DECLARE finished INTEGER DEFAULT 0;
DECLARE loop_count int(4);
DECLARE upc varchar(32);
DECLARE p_product_id int(11);
DECLARE p_model varchar(64);
DECLARE counter_cursor CURSOR FOR
SELECT product_id,model,quantity FROM product
WHERE model in('CFB0040','CFB0042','CFB0043','CFB0044')
AND quantity > 0;
DECLARE CONTINUE HANDLER FOR 1062
SET message = 'Duplicate Keys Found';
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET finished = 1;
OPEN counter_cursor;
add_data : LOOP
FETCH counter_cursor INTO p_product_id, p_model, loop_count;
SET i = 1;
WHILE loop_count > 0 DO
CASE i
WHEN i < 10 THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-000',i);
WHEN (i >= 10 AND i < 100) THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-00',i);
WHEN (i >= 100 AND i < 1000) THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-0',i);
ELSE
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-',i);
END CASE;
INSERT INTO product_universal_description
(
`upc_id`,
`po_id`,
`supplier_id`,
`location_id`,
`warehouse_id`,
`product_id`,
`model_no`,
`added_by`,
`updated_by`,
`date_added`,
`date_modified`
) VALUES (
temp_upc,
s_po_id,
s_supplier_id,
s_location_id,
s_warehouse_id,
p_product_id,
p_model,
s_user_id,
s_user_id,
NOW(),
NOW()
);
SET i=i+1;
SET loop_count = loop_count - 1;
END WHILE;
IF finished = 1 THEN
LEAVE add_data;
END IF;
END LOOP add_data;
CLOSE counter_cursor;
END
CALL veealpha(123,45,'UP',1,56,#msg,#err);
ON Execution I getting the result like this.
How ever I have given the conditions there for UPC_ID that it should be well mannered as per case. But leaving for i = 1 FOR all it takes the ELSE condition at CASE. Can anybody tell me .. what's wrong happened and how could i get the desired result.
Try:
...
-- CASE i
CASE
WHEN i < 10 THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-000',i);
WHEN (i >= 10 AND i < 100) THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-00',i);
WHEN (i >= 100 AND i < 1000) THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-0',i);
ELSE
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-',i);
END CASE;
...

Mysql : Not allowed to return a result set from a function

I have write one function but getting this error Not allowed to return a result set from a function
DELIMITER $$
CREATE FUNCTION getTestFunction
(
p_ParentID int,
p_ListName nvarchar(50),
p_Type nvarchar(50),
p_Count int
)
RETURNS nvarchar(2000)
BEGIN
DECLARE p_KeyValue nvarchar(2000);
DECLARE p_ListValue nvarchar(2000);
DECLARE p_TextValue nvarchar(2000);
DECLARE p_ReturnValue nvarchar(2000);
DECLARE p_Key nvarchar(2000);
IF p_ParentID = 0 THEN
IF p_Count = 0 THEN
SET p_ReturnValue = '';
ELSE
SET p_ReturnValue = p_ListName;
END IF;
ELSE
SELECT p_KeyValue = ListName + '.' + Value
FROM ListsTable
WHERE EntryID = p_ParentID LIMIT 1 ;
RETURN p_ReturnValue;
If p_Type = 'ParentKey' Or (p_Type = 'ParentList' AND p_Count > 0) THEN
SET p_ReturnValue = p_KeyValue;
ELSE
IF p_Type = 'ParentList' THEN
SET p_ReturnValue = p_ListValue;
ELSE
SET p_ReturnValue = p_TextValue;
END IF;
END IF;
IF p_Count > 0 THEN
If p_Count = 1 AND p_Type = 'ParentList' THEN
SET p_ReturnValue = p_ReturnValue + ':' + p_ListName;
ELSE
SET p_ReturnValue = p_ReturnValue + '.' + p_ListName;
END IF;
END IF;
END IF;
RETURN p_ReturnValue;
END$$
DELIMITER ;
You want to assign the result of a query to a variable, but in fact you're just selecting. That's why MySQL's complaining.
You have to change this
SELECT p_KeyValue = ListName + '.' + Value
FROM ListsTable
WHERE EntryID = p_ParentID LIMIT 1 ;
to
SELECT CONCAT(ListName, '.', `Value`)
INTO p_KeyValue
FROM ListsTable
WHERE EntryID = p_ParentID LIMIT 1 ;
And you should add an ORDER BY. A LIMIT without ORDER BY doesn't make sense, since there's no guaranteed order in a relational database.
Mysql complains about SELECT statement in your function,
probably it understands SELECT p_KeyValue = ListName + '.' + Value as comparison
change it to
SELECT CONCAT(ListName, '.', Value) INTO p_KeyValue

Mysql cursor fetches only first row

Mysql cursor fetches only first row and when it has fetched the second row the row_not_found variable is set to false and cursor close.
Please look into below SP:
CREATE DEFINER = 'root'#'localhost'
PROCEDURE billingv2test.SP_CreateRecurringBillingOrders(IN _billingDate DATETIME,
IN _defaultBillingFrequency INT,
IN _IsForcedExecution BIT)
BEGIN
DECLARE _userId char(36);
DECLARE _billingStartDate datetime;
DECLARE _billingEndDate datetime;
DECLARE _cmd VARCHAR(4000);
DECLARE _userBillingHistoryId char(36);
DECLARE _paymentOrderId char(36);
DECLARE _orderNumber VARCHAR(100);
DECLARE _totalChargeAmount DECIMAL(15, 6);
DECLARE _couponChargeAmount DECIMAL(15, 6);
DECLARE _pendingChargeAmount DECIMAL(15, 6);
DECLARE _isError BIT;
DECLARE _noOfUsersProcessed BIT;
DECLARE _billingResourceType VARCHAR(20);
DECLARE _RowNo INT;
DECLARE _defaultDateTime DATETIME;
DECLARE record_not_found INTEGER DEFAULT 0;
DECLARE user_list varchar(200);
DECLARE ProcessUsersForRecurringBilling_Cursor CURSOR FOR
SELECT OwnerId FROM UserBillingInfo
WHERE NextBillingDate IS NOT NULL
AND cast(NextBillingDate as date) <= cast( _billingDate as date)
AND IsProcessPending = 0
AND IsDeleted = 0
AND BillingStatus <> 'Delinquent'
ORDER BY NextBillingDate;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET record_not_found = 1;
SET _isError = 0;
SET _noOfUsersProcessed = 0;
SET _defaultDateTime = '1900-01-01 00:00:00';
SET _userBillingHistoryId = UUID();
INSERT INTO BillingHistory( Id, BillingStartTime, BillingEndTime, Status, NoOfUsersProcessed, CreateTime, UpdateTime )
VALUES ( _userBillingHistoryId, UTC_TIMESTAMP(), NULL , 'Started', 0, UTC_TIMESTAMP(), UTC_TIMESTAMP());
OPEN ProcessUsersForRecurringBilling_Cursor;
allusers: LOOP
FETCH ProcessUsersForRecurringBilling_Cursor INTO _userId;
IF record_not_found THEN
LEAVE allusers;
END IF;
SET user_list = CONCAT(IFNULL(user_list,''),", ",_userId);
SET _isError = 0;
SET _orderNumber = '';
SET _totalChargeAmount = '0';
SET _couponChargeAmount = '0';
SET _pendingChargeAmount = '0';
UPDATE UserBillingInfo SET IsProcessPending = 1 WHERE OwnerId = _userId;
SET _billingStartDate = _defaultDateTime;
SELECT
IFNULL(InvoiceDate, _defaultDateTime) INTO _billingStartDate
FROM
PaymentOrder
WHERE OwnerId = _userId AND OrderStatus IN ('Success', 'Submitted')
ORDER BY CreateTime DESC
LIMIT 1;
SELECT NextBillingDate INTO _billingEndDate FROM UserBillingInfo WHERE OwnerId = _userId;
SET _orderNumber = UUID();
SET _orderNumber = SUBSTRING(_orderNumber, 0, LOCATE('-', _orderNumber));
-- CALL SP_CreateRecurringBillingPaymentOrder
CALL SP_CreateRecurringBillingPaymentOrder
(_userId, _billingStartDate, _billingEndDate, _orderNumber, _userBillingHistoryId, _paymentOrderId);
SELECT Amount INTO _totalChargeAmount FROM PaymentOrder WHERE Id = _paymentOrderId;
SET _pendingChargeAmount = _totalChargeAmount;
UPDATE PaymentOrder set ChargeAmount = _pendingChargeAmount, UpdateTime = UTC_TIMESTAMP()
WHERE Id = _paymentOrderId;
UPDATE ResourceUsageProcessed SET BillingStatus = 'Completed'
WHERE PaymentOrderId = _paymentOrderId AND BillingStatus = 'Processing';
SET _noOfUsersProcessed = _noOfUsersProcessed + 1;
END LOOP allusers;
CLOSE ProcessUsersForRecurringBilling_Cursor;
UPDATE BillingHistory SET NoOfUsersProcessed = _noOfUsersProcessed, Status = 'Completed', BillingEndTime = UTC_TIMESTAMP()
WHERE Id = _userBillingHistoryId;
END
hey this may sound silly but try this
IF record_not_found=1 THEN
LEAVE allusers;

MsSQL to MySQL function conversion

So I am trying to convert a function I created in MSSQL to MYSQL. The way I have it written in MSSQL is:
ALTER function FormatDate(#date datetime) returns varchar(10)
begin
declare #salida varchar(10)
if (#date != '') and (#date != '01/01/1900')
begin
declare #day varchar(2)
set #day = cast(day(#date) as varchar)
if len(#day) = 1
set #day = '0' + #day
declare #month varchar(2)
set #month = cast(month(#date) as varchar)
if len(#month) = 1
set #month = '0' + #month
select #salida = #month + '/' + #day + '/' + cast(year(#date) as varchar)
end
else
set #salida = null
return #salida
end
I am trying to convert that function into a MYSQL function. I tried this:
Delimiter $$
create function FormatDate(tiempo datetime)
RETURNS varchar(10)
READS SQL DATA
BEGIN
declare salida varchar(10);
if ((tiempo != '') and (tiempo != '01/01/1900')) then
BEGIN
declare dia varchar(2);
set dia = cast(day(tiempo) as varchar);
if len(dia) = 1 then
set dia = '0' + dia;
END IF;
declare mes varchar(2);
set mes = cast(month(tiempo) as varchar);
if len(mes) = 1 then
set mes = '0' + mes;
END IF;
select salida = mes + '/' + dia + '/' + cast(year(tiempo) as varchar);
else
set salida = null;
END; End if;
return (salida);
END $$
Delimiter ;
but I get an error when I try to execute that code.
This is the error I am getting:
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 'varchar);
if len(dia) = 1 then
' at line 14
Can someone please help me convert this MSSQL function into a MYSQL function?
The function to determine a strings lenght in MySQL is called LENGTH(), not len()
http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length
MORE:
I added a working version of your function below. But please note that the built-in function DATE_FORMAT() does exactly what you want:
mysql> SELECT FormatDate( NOW() ), DATE_FORMAT( NOW(), "%m/%d/%Y" );
+---------------------+----------------------------------+
| FormatDate( NOW() ) | DATE_FORMAT( NOW(), "%m/%d/%Y" ) |
+---------------------+----------------------------------+
| 07/15/2011 | 07/15/2011 |
+---------------------+----------------------------------+
You should either use it or replace your function body with a call of that function. Here is, however, a MySQL compatible version of your function:
DELIMITER $$
CREATE FUNCTION `FormatDate`(tiempo datetime) RETURNS varchar(10)
READS SQL DATA
BEGIN
DECLARE salida VARCHAR(10);
DECLARE dia VARCHAR(2);
DECLARE mes VARCHAR(2);
IF ( (tiempo <> '') AND ( tiempo <> '01/01/1900' ) ) THEN
SET dia := CAST( DAY( tiempo ) AS CHAR );
IF LENGTH( dia ) = 1 THEN
SET dia := CONCAT( '0', dia);
END IF;
SET mes := CAST( MONTH( tiempo ) AS CHAR );
IF LENGTH( mes ) = 1 THEN
SET mes := CONCAT( '0', mes );
END IF;
SET salida := CONCAT_WS( '/', mes, dia, CAST( YEAR( tiempo ) AS CHAR ) );
ELSE
SET salida := NULL;
END IF;
RETURN salida;
END $$
DELIMITER ;