looking for a subtle way to increment variable in SQL 2005

hello experts,

    i am trying to increment counter within SQL 2005

 for example, instead of doing

SELECT  1 UNION
SELECT  2 UNION
SELECT 3

I want to do

DECLARE @i smallint; SET @i = 1; -- instant initialization in SQL 2005 does not fly, i gather

INSERT INTO temp
SELECT @i UNION
SELECT @i++ UNION   --  this is just an improvisation
SELECT @i++  -- ????

i think, in 2008 and 2012 they have cool shortcuts to do this, but what about SQL 2005
i would prefer not to do SET @i = @i + 1 in between every time

thanks in advance
AlexF777Asked:
Who is Participating?
 
EvilPostItConnect With a Mentor Commented:
Identity column was what I was leaning towards. That makes the most sense.
0
 
EvilPostItConnect With a Mentor Commented:
Are you talking about an auto increment or inserting a set a data and generating an ascending ID against that?
0
 
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
You're going to have to paint us a bigger picture of what you're trying to pull off here.
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
AlexF777Author Commented:
autoincrement: i want each consequitive SELECT statement to use the next value: i.e.
1, 2, 3, ...
0
 
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
>i would prefer not to do SET @i = @i + 1 in between every time
Unless you can paint us a bigger picture of what your trying to pull off, this is the only solution that is guaranteed to work.

You could have an identity column in your table, but it will incriment on rows, not on INSERT statements that created those rows, so that works only if your INSERTS insert one row at a time.
0
 
AlexF777Author Commented:
no, i want to increment my variable in memory
with SQL 2008 i could say

SELECT @i UNION
SELECT @i+= 1 UNION

actually, i probably could use an identity column: i could insert all my rows into the temp
table, then do an INSERT into a live table FROM SELECT and that will probably do it ...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.