cancel
Showing results for 
Search instead for 
Did you mean: 

Increment Value in FOR Loop in sap hana

Former Member
0 Kudos

Hi All,

The default incremented value for FOR loop is 1 (shown in the below example). Is there any way to modify it?

In the below example, the value of i gets incremented by 1 each time, i would like to increment it by '2'  (or '3'). 

Create procedure forrr(IN inval INT, out val int)

as

i int :=0;

begin

Declare  a1 int default 0;

  For i in 1..inval DO

  a1:=a1+i;

  End For;

  Val:=a1;

end;

Call forrr(5,?)---> Output is: 15 (sum of digits from 1 to 5)

I tried with a statement i:=i+1; after   a1:=a1+i;  but it is throwing the below error:


Error: Could not execute 'Create procedure forrr(IN inval INT, out val int) as i int :=0; begin Declare a1 int default 0; For ...' in 446 ms 111 µs .

SAP DBTech JDBC: [1288] (at 135): expression cannot be used as an assignment target: I: line 8 col 3 (at pos 135)

I am looking forward for your inputs.

Thanks,

Sree

Accepted Solutions (0)

Answers (2)

Answers (2)

Former Member
0 Kudos

Hi, all.

Another variant:

Create procedure forrr(IN inval integer,step integer, out val int)

as

begin

declare v_index1 integer;

v_index1:=0;

val:=0;

WHILE :v_index1 < :inval DO

v_index1:=:v_index1+:step;

val:=:val+1;

END WHILE;

end;

Former Member
0 Kudos

Thank you so much !!

I am able to get what I want (slightly modifying your code snippet)

Thanks,

Sree

Former Member
0 Kudos

Hi Sree,

I just copied your code and ran it successfully.

Best regards,

Wenjun

Former Member
0 Kudos

Hi Wenjun,


I was trying to run the below code. I know What ever i pasted earlier runs without any issue.


Please try run the following.


Create procedure forrr(IN inval INT, out val int)

as

i int :=0;

begin

Declare  a1 int default 0;

  For i in 1..inval DO

  a1:=a1+i;

i:=i+1;

  End For;

  Val:=a1;

end;


Thanks,

Sree

Former Member
0 Kudos

Hi Sree,

As the error message implies, i is an expression and cannot be used as assignment target. You cannot change i in the for loop manually.

You can have a look at For Loop - SAP HANA SQLScript Reference - SAP Library

"The for loop iterates a range of numeric values and binds the current value to a variable <loop-var>

in ascending order. Iteration starts with the value of <start_value> and is incremented by one until the <loop-var> is greater than <end_value> ."

So, you cannot increment it by 2 or 3.

Best regards,

Wenjun