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
:
After the update my data should look like this:
I could write a loop for this, but I'm hoping for something smaller and more efficient. Any ideas?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With