简体   繁体   English

MSSQL 控制序列

[英]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.如果我有一个从 1 到 10000 的编号序列,并且我想在 100 和 101 之间插入一行。或者我想将 99 移动到 1 和 2 之间。

Can this be managed in SQL or do i need to manage it in the programmatically.这可以在 SQL 中管理还是我需要以编程方式管理它。

SQL Server tables do not have any implicit order! SQL Server 表没有任何隐式顺序!

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 )添加一列 SortKey BIGINT (用值填充后,您应该将其设置为NOT NULL并创建一个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. SQL 不会以任何特定顺序在表中存储数据,当您使用索引或其他查询查看数据时,它只是以这种方式存储。 You'd have to have an ID column that you use to sort the data.您必须有一个用于对数据进行排序的 ID 列。 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<).在两个当前行之间插入数据并不容易(例如,在 100 和 101 之间插入需要您重新编号所有 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.如果这当然不完美,因为您可能会耗尽您的行内间隙,但这是一个开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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