简体   繁体   English

SQL Server:添加增量值(不是身份)

[英]SQL Server: add incremental value (not identity)

I have a table and I want to insert some rows. 我有一张桌子,我想插入一些行。 There is a column num which is not identity. 没有编号的列num When the insertion of new rows takes place I want the num value to be incremented by 1 starting from the highest existing value. 当插入新行时,我希望num值从现有的最高值开始增加1。 Here is my code until now: 到目前为止,这是我的代码:

insert into table1 ( num, val)
select (( select max(num) from table1) + row_number() over (order by num)), val
from table1

Here is the error I get: 这是我得到的错误:

Subquery returned more than 1 value. 子查询返回的值超过1。 This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. 当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

UPDATE The error comes from the trigger so I posted a new question regarding the trigger: SQL Server 2012 trigger: Doesnt work with multiple rows inserted 更新错误来自触发器,因此我发布了有关触发器的新问题: SQL Server 2012触发器:不适用于插入的多行

You should be using window functions instead of a subquery: 您应该使用窗口函数而不是子查询:

insert into table1 (num, val)
    select ( max(num) over () + row_number() over (order by num) ), val
    from table1;

However, the query in your question cannot return that error, because an aggregation query with no group by always returns exactly one row. 但是,您问题中的查询无法返回该错误,因为没有group by的聚合查询总是返回恰好一行。

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

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