Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to update existing records with a sequence?

I've got a data set with a primary key, a foreign key and an empty sequence value. What is the fastest way of adding a sequence number to the data based on the foreign key?

QuestionConditionId is my primary key, QuestionId is foreign key. This is what the data looks like after selecting with an order by on QuestionId:

enter image description here

After the update my data should look like this:

enter image description here

I could write a loop for this, but I'm hoping for something smaller and more efficient. Any ideas?

like image 934
Mark Avatar asked Jan 18 '13 12:01

Mark


People also ask

How do you update a sequence in SQL Server?

Sequences objects are created by using the CREATE SEQUENCE statement. Sequences are integer values and can be of any data type that returns an integer. The data type cannot be changed by using the ALTER SEQUENCE statement. To change the data type, drop and create the sequence object.

How can I update 1 million records in SQL Server?

DECLARE @Rows INT, @BatchSize INT; -- keep below 5000 to be safe SET @BatchSize = 2000; SET @Rows = @BatchSize; -- initialize just to enter the loop BEGIN TRY WHILE (@Rows = @BatchSize) BEGIN UPDATE TOP (@BatchSize) tab SET tab. Value = 'abc1' FROM TableName tab WHERE tab. Parameter1 = 'abc' AND tab.

How do I add a sequence number in SQL?

The syntax to create a sequence in SQL Server (Transact-SQL) is: CREATE SEQUENCE [schema.] sequence_name [ AS datatype ] [ START WITH value ] [ INCREMENT BY value ] [ MINVALUE value | NO MINVALUE ] [ MAXVALUE value | NO MAXVALUE ] [ CYCLE | NO CYCLE ] [ CACHE value | NO CACHE ]; AS datatype.


1 Answers

WITH T
     AS (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY QuestionId 
                                       ORDER BY QuestionConditionId ) AS RN
         FROM   YourTable)
UPDATE T
SET    Sequence = RN 

But keeping this Sequence column synchronised after inserts, updates, deletes may be more hassle than it is worth. You can also use ROW_NUMBER to calculate at SELECT time rather than storing it.

like image 94
Martin Smith Avatar answered Oct 10 '22 21:10

Martin Smith