Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Increment a number in a select statement

  • 15-10-2008 03:49PM
    #1
    Closed Accounts Posts: 196 ✭✭


    Hi im stuck in this

    i need to increment a number in a select statement

    i cant use an autonum as i dont want to change the database table structure

    ie



    select field 1 , field 2 , inremented_field from table

    should result in

    field 1 field 2 0
    field 1 field 2 1
    field 1 field 2 2
    field 1 field 2 3

    any ideas ?


Comments

  • Moderators, Society & Culture Moderators Posts: 9,688 Mod ✭✭✭✭stevenmu


    Try
    SELECT field1, field2, ROW_NUMBER() OVER(ORDER BY field1) as incremented_field
    FROM table
    

    That'll work in SQL Server at least.


  • Closed Accounts Posts: 196 ✭✭NedKelly


    tried that in sql server 2000 and i get

    Server: Msg 195, Level 15, State 10, Line 1
    'ROW_NUMBER' is not a recognized function name.


  • Registered Users, Registered Users 2 Posts: 2,494 ✭✭✭kayos


    SELECT ROWID=IDENTITY(int,1,1) , * 
    INTO #tmp FROM table ORDER BY Field1
    
    SELECT * FROM #tmp
    
    

    That should work in 2000


  • Moderators, Society & Culture Moderators Posts: 9,688 Mod ✭✭✭✭stevenmu


    Ah yes, it was only introduced in 2005. Not very efficient but can you create a temp table with an identity column and select into that ?


  • Registered Users, Registered Users 2 Posts: 1,453 ✭✭✭showry


    You could do something like this provided you were ordering by a unique key
    SELECT name,
    (
    SELECT COUNT( * )
    FROM t_test t2
    WHERE t2.id < t1.id
    )
    FROM t_test t1
    ORDER BY id


  • Advertisement
  • Closed Accounts Posts: 2,268 ✭✭✭mountainyman


    declare @rowNumber
    then set a cursor MyCursor
    Then
    set @RowNum = 0 
    
    	WHILE @@FETCH_STATUS = 0
    	BEGIN
    	  set @RowNum = @RowNum + 1
    
    	  FETCH NEXT FROM MyCursor
    
    


Advertisement