sql variable as array index

hi folks
i am facing problom while trying to access sql variable as array index ina unix shell script....script goes as below..

#!/bin/ksh
MAX=3
for elem in alpha beeta gaama
do
arr[$x]=$elem
((x=x+1))
Done

SQL_SERVER='servername'
/apps/sun5/utils/sqsh -S $SQL_SERVER -U user -P pwd -b -h <<EOF
set nocount on
go
use DBname
go
declare @MaxID int
set @MaxID=0
print $MAX
while @MaxID < $MAX
begin
print ${arr[@MaxID]}
set @MaxID=@MaxID+1
end
print 'endof while'
go
EOF

Is the script...
Prob is not able to use @MaxId as array subscript since it is a sql variable and array is used inside sqsh mode i.e sql prompt ...

Any way to access the unix array in side sql prompt based on index....???? Hope i made my self clear.

Thanks in advance.

This wont work because of scope issues. The array $arr[..] is declared in the shell, so it has to be interpreted by the shell. When you try to send it into sqsh's STDIN it won't be able to expand it since at that time the shell has no idea what value the SQL variable @foo will have.

One way of solving this (very ugly, but I have seen it in the wild) is to write some SQL code which generates some ksh code which (yes I said it was gawdugly) creates SQL code.

Don't do this. It might work but someone is going to have to maintain it. Prolly you.

Instead ask yourself why you are using an array in ksh in the first place. Could you use a file? A table in the DB? Is the data available from the inside of a SQL session?