cancel
Showing results for 
Search instead for 
Did you mean: 

Unable to fetch Distinct values into the For loop in SAP HANA.

Vamshi9
Discoverer
0 Kudos

I am trying to fetch Distinct values into the For loop in SAP HANA using CURSOR and For Loop and I am not getting all the distinct values into the For Loop. Instead of getting 10 distinct names, I am getting only 5 names in my output. Could you please guide me with the correct SQL?

CREATE PROCEDURE DBADMIN.FetchDistinctStrings()
LANGUAGE SQLSCRIPT
AS
BEGIN
        DECLARE STRING1 VARCHAR(255);
        DECLARE CURSOR MyTenIDFetch (STRING1 VARCHAR(255)) FOR
        SELECT DISTINCT EMPLOYEE_NAMES FROM "H_CPO_MAIN"."TABLE_NURO";
        OPEN MyTenIDFetch(:STRING1);
        FETCH MyTenIDFetch INTO STRING1;
        FOR CUR_ROW AS MyTenIDFetch(STRING1) DO
        SELECT STRING1 as STRING_NAMES FROM DUMMY;
        END FOR;
    CLOSE MyTenIDFetch;
END;
RobertWaywell
Product and Topic Expert
Product and Topic Expert
0 Kudos
The most likely reason for only getting 5 names is that the query " SELECT DISTINCT EMPLOYEE_NAMES FROM "H_CPO_MAIN"."TABLE_NURO";" is only returning 5 values. Have you run the query outside of the procedure to check the result set?

Accepted Solutions (1)

Accepted Solutions (1)

Vamshi9
Discoverer

@RobertWaywell 

I ran the SQL outside and I am getting 10 results. But anyway, I found that my logic is incorrect. 

When using CURSOR, we shouldn't (no need) use OPEN, FETCH commands. Achieved the logic by below procedure. 

 

 

 

CREATE PROCEDURE DBADMIN.FetchDistinctStrings(IN DAYS INT)
LANGUAGE SQLSCRIPT
AS
BEGIN
        DECLARE STRING1 VARCHAR(255);
        DECLARE CURSOR MyTenIDFetch (STRING1 VARCHAR(255)) FOR
        SELECT DISTINCT EMPLOYEE_NAMES FROM "H_CPO_MAIN"."TABLE_NURO";
        FOR CUR_ROW AS MyTenIDFetch(STRING1) DO
        SELECT :CUR_ROW.STRING1 as STRING_NAMES FROM DUMMY;
        END FOR;
END;

 

 

Answers (0)