Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : increment INT column using variable

Tags:

sql

sql-server

Trying to insert an order column into some records, based on another field. Normally not a problem in MySQL, but in SQL Server I can't quite understand the syntax here.

This is what I have:

DECLARE @a int
SET @a = 1

UPDATE tablename 
SET order_position = @a:=@a+1  
WHERE table_id = xxx

But part of me thinks this is going down the route of a function/procedure as opposed to a one hit UPDATE query.

Sorry, but I wrote this as a MySQL database person, not familiar with variables with SQL Server so could be a little wrong.

I need to run this on a load of records one by one, and I want the order_position column to be 1-7 (where there are 7 records), etc..

Thanks, Chris

like image 733
Chris Avatar asked Aug 01 '13 16:08

Chris


People also ask

How can I increment a column value in SQL?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

Can we use += in SQL?

+= (Addition Assignment) (Transact-SQL)Adds two numbers and sets a value to the result of the operation. For example, if a variable @x equals 35, then @x += 2 takes the original value of @x, add 2 and sets @x to that new value (37).

How do I create an existing column auto-increment in SQL?

ALTER TABLE Inventory MODIFY COLUMN item_number INT AUTO_INCREMENT=50; After running this code, future item IDs will start at an item_number of 50 and increment by 1. To change the starting increment value and increment in SQL Server, set your non-default values during table creation.


2 Answers

Try this code:

DECLARE @a int
SET @a = 1
UPDATE tablename SET order_position = @a, @a=@a+1  WHERE table_id = xxx

You are trying to do a double assignment which is the issue. "order_position = @a:=@a+1" has 2 interpretations, one you know and the other is that the result of incrementing a, that it succeeded is what should go in the order_position value.

like image 96
JB King Avatar answered Oct 16 '22 10:10

JB King


Separate the variable incrementing from the field update.

DECLARE @a int
SET @a = 1
UPDATE tablename 
SET order_position = @a
   ,@a = @a + 1  
WHERE table_id = xxx

Coming from MySQL you may be overlooking a great tool for this task, ROW_NUMBER().

You can use ROW_NUMBER() to assign a number to each row in a table:

SELECT *,ROW_NUMBER() OVER (PARTITION BY ....  ORDER BY .... )
FROM Table

PARTITION BY indicates a grouping for numbering, ie there will be a '1' for each combination of fields used in the PARTITION BY, and they will of course be ordered from 1-n based on the ORDER BY clause.

like image 43
Hart CO Avatar answered Oct 16 '22 08:10

Hart CO