Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Increment a number in a select statement

Options
  • 15-10-2008 3: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,689 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 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,689 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 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