sql-server - TSQL 使用序列插入表

标签 sql-server tsql sql-order-by sequence

我正在努力理解下面的内容,

INSERT INTO Sales.MyOrders(orderid, custid, empid, orderdate) 
SELECT NEXT VALUE FOR Sales.SeqOrderIDs OVER(ORDER BY orderid),
       custid,
       empid,
       orderdate
FROM Sales.Orders
WHERE custid = 1; 

书上说

OVER clause with an ORDER BY list to control the order in which the sequence values are assigned to the result rows

如果我能得到澄清那就太好了

最佳答案

来自 NEXT VALUE FOR (Transact-SQL)

Generates a sequence number from the specified sequence object.

Sequence Numbers

A sequence is a user-defined schema-bound object that generates a sequence of numeric values according to the specification with which the sequence was created. The sequence of numeric values is generated in an ascending or descending order at a defined interval and may cycle (repeat) as requested. Sequences, unlike identity columns, are not associated with tables. An application refers to a sequence object to receive its next value. The relationship between sequences and tables is controlled by the application. User applications can reference a sequence object and coordinate the values keys across multiple rows and tables.

这是 SQL Server 2012 中的新功能,它允许多个表使用相同的标识序列,以允许跨不同表的唯一 ID。

SQL Fiddle DEMO

看一下随附的 DEMO,您将看到如何在表中使用 autonumber 的效果。

OVER ORDER BY 只是确保指定生成序列的顺序。

SQL Fiddle DEMO

上面的演示应该说明如何根据原始 ID 的顺序分配序列。

关于sql-server - TSQL 使用序列插入表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19313622/

相关文章:

sql-server - GRANT 的 "AS DBO"部分有什么作用?

sql - XML 到 SQL - 选择多个同名节点

c# - 我应该在 T-SQL 中进行错误处理吗?

sql - T-SQL 中是否有 LIKE 语句的替代方法?

oracle - 如何解决 ORA-02014 : cannot select FOR UPDATE from view with DISTINCT, GROUP BY 等问题

mysql - MySQL 中的 SQL 排序

SQL Server 中的 MySQL\G 等价物

SQL:删除值已存在的行

sql - 重用表变量?

php - MYSQL IF 语句按类别重新排序