简体   繁体   中英

MSSQL controlling sequence

I need a method for managing sequences in a table. i have a table that needs to be managed by a sequence. I must be able to insert a row between two other rows. if i have a numbered sequence from 1 to 10000, and i want to insert a row between 100 and 101. Or i want to move 99 to between 1 and 2.

Can this be managed in SQL or do i need to manage it in the programmatically.

SQL Server tables do not have any implicit order!

The only way to enforce a sequence is a sortable column (or a combination of columns) with unique values.

One way to achieve this was to number your row after an existing sort key:

  • add a column SortKey BIGINT (after filling it with values you should set it to NOT NULL and create an unique index )

This fully working example will show you how to do this:

CREATE TABLE #Dummy(SomeExistingSortField INT, SomeContent VARCHAR(100));
INSERT INTO #Dummy VALUES(3,'insert first'),(1,'insert second'),(2,'insert third');

SELECT * FROM #Dummy;

ALTER TABLE #Dummy ADD SortKey BIGINT;

WITH CTE AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT SomeExistingSortField)) * 10 AS nr
          ,SortKey
    FROM #Dummy
)
UPDATE CTE SET SortKey=nr;

SELECT * FROM #Dummy ORDER BY SortKey;

INSERT INTO #Dummy VALUES(99,'between 1 and 2',15);

SELECT * FROM #Dummy ORDER BY SortKey;

WITH CTE AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT SortKey)) * 10 AS nr
          ,SortKey
    FROM #Dummy
)
UPDATE CTE SET SortKey=nr;

SELECT * FROM #Dummy ORDER BY SortKey;

GO
DROP TABLE #Dummy;

SQL doesn't store data in any particular order in the table, it just appears that way when you look at data using an index or other query. You'd have to have an ID column that you use to sort the data. It won't be easy to insert data between two current rows (eg to insert between 100 and 101 would require you to re-number everything 101<).

One way to accomplish this would be to have your sequence be non-contiguous. That is, specify an increment on the sequence to leave gaps enough to put your interleaving rows. If course this isn't perfect as you may exhaust your intra-row gaps, but it's a start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM