1

How do I create/declare variables with a counter in the name on a MS SQL Server? I have a "for-like" loop with CURSOR and

WHILE @@FETCH_STATUS = 0

BUT: the number of those values is changing continuously. So i want to write every value in an own variable. My goal is to get var-names like : @var1, next loop @var2, next @var3 etc. Well

SET @counter = (@counter + 1)

is not THAT difficult, but how do I add the value(!) of @counter to the name(!) of @var?

THX a LOT!

Michael
  • 3,982
  • 4
  • 30
  • 46
Agen T Smith
  • 49
  • 1
  • 6
  • 2
    Why would you want to do that? If you are trying to imitate arrays I suggest you use a table-variable instead. – hsan Feb 18 '13 at 14:05

2 Answers2

2

I think you should create a temp table to store these variables. For example:

DECLARE @ValTable TABLE
(
  ID int,
  Val int, -- or any type you need
)

Now insert a new value:

SET @counter = (@counter + 1);
INSERT INTO @ValTable VALUES (@counter, <VALUE>);

To get this value [i] use simple select:

SELECT Val FROM @ValTable where ID=<Number of value here>;
valex
  • 23,966
  • 7
  • 43
  • 60
  • Thank you very much for your answer. :) I thought of it too, but I would expect, that using cursors needs less performance than using temp tables... or am I wrong? – Agen T Smith Feb 18 '13 at 14:10
  • 1
    @AgenTSmith So a cursor has less overhead. Cursor does not support creating a variable run time nor arrays. – paparazzo Feb 18 '13 at 15:46
0

I don't really understand what you are trying to achieve, but a way to do it would be to build the query string within your for loop as you want it to be than execute it to get the result formatted as you want it.

HucKQC
  • 61
  • 9