Is it possible for me to Declare cursor inside if statement?
if possible how could i make it?
because i just made cursor like this
CREATE FUNCTION `fn_test`(
ProductID BIGINT(20)
)
RETURNS DECIMAL(10,2)
BEGIN
DECLARE PrductDiscValue DECIMAL(10, 2);
DECLARE DiscType INT(1);
DECLARE DiscValue DESIMAL(10,2);
IF ProductID != 0 THEN
SET PrductDiscValue = (SELECT Discountvalue, DiscountType FROM discount WHERE FIND_IN_SET(ProductID,DiscIDs);
END IF;
RETURN ProductDiscountValue(1);
But this is not working. So, I do the following
IF ProductID != 0 THEN
DECLARE PrductDiscValue CURSOR FOR SELECT Discountvalue, DiscountType FROM discount WHERE FIND_IN_SET(ProductID,DiscIDs;
END IF;
OPEN ProductDiscountValue;
FETCH ProductDiscountValue INTO DiscValue, DiscType;
RETURN DiscValue;
END
And this gives me error ::
I need the both DiscValue and DiscType for different calculation.
Any Help would be appreciate
Thanks in advance.
MySQL supports cursors inside stored programs. The syntax is as in embedded SQL. Cursors have these properties: Asensitive: The server may or may not make a copy of its result table.
When working with MySQL cursor, you must also declare a NOT FOUND handler to handle the situation when the cursor could not find any row. Because each time you call the FETCH statement, the cursor attempts to read the next row in the result set.
DECLARE CURSOR defines the attributes of a Transact-SQL server cursor, such as its scrolling behavior and the query used to build the result set on which the cursor operates. The OPEN statement populates the result set, and FETCH returns a row from the result set.
Please, use it:
BEGIN
IF test = true THEN
BEGIN
DECLARE ats_cursor CURSOR FOR SELECT distinct ats_id FROM ats_eb ats where ats.year = year and ats.edition_shortname = edition;
END;
ELSE
BEGIN
DECLARE ats_cursor CURSOR FOR SELECT distinct ats_id FROM ats_eb ats where ats.year = year and ats.edition_shortname = edition;
END;
END IF;
END
even I never used CURSOR so far in MySQL, But what I found is that , it is clearly mentioned on MySQL manual
Cursor declarations must appear before handler declarations and after variable and condition declarations.
if you want to use that cursor on some condition then you must use FETCH CURSOR syntax in IF condition
below are some good tutorial which will describe the cursor in details:
CURSOR in mySQL stored procedure
MySQL CURSOR Tutorial
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With