Access columns of a table by index instead of name in SQL Server stored procedure

edgarmtze picture edgarmtze · Feb 3, 2011 · Viewed 53.2k times · Source

Is there a way to access columns by their index within a stored procedure in SQL Server?

The purpose is to compute lots of columns. I was reading about cursors, but I do not know how to apply them.

Let me explain my problem:

I have a row like:

field_1 field_2 field_3 field_4 ...field_d  Sfield_1 Sfield_2 Sfield_3...Sfield_n
1       2       3       4          d        10       20       30         n

I need to compute something like (field_1*field1) - (Sfield_1* Sfiled_1) / more...

So the result is stored in a table column d times.

So the result is a d column * d row table.

As the number of columns is variable, I was considering making dynamic SQL, getting the names of columns in a string and splitting the ones I need, but this approach makes the problem harder. I thought getting the column number by index could make life easier.

Answer

OMG Ponies picture OMG Ponies · Feb 3, 2011

No, you can not use the ordinal (numeric) position in the SELECT clause.

Only in the ORDER BY clause can you use the ordinal position, because it's based on the column(s) specified in the SELECT clause.