【问题标题】:How can I increment the value for each INSERT INTO iteration?如何增加每次 INSERT INTO 迭代的值?
【发布时间】:2013-08-10 08:01:05
【问题描述】:

我有一个查询,如下所示 column1 是整数 另一列是 varchar(100)

INSERT INTO TABLE1 (column1,column2)
SELECT (MAX(column1) FROM TABLE1)+1 ,anotherColumn FROM TABLE2

查询前的表1

column1  column2
-------  -------
3         test1
4         test2

查询后的表1

column1  column2
-------  -------
3         test1
4         test2
5         anotherVal1
5         anotherVal2
5         anotherVal3

但我想要

column1  column2
-------  -------
3         test1
4         test2
5         anotherVal1
6         anotherVal2
7         anotherVal3

如何在 SQLserver 2008 StoredProcedure 中实现这一点? 我一直认为查询是迭代的,他们会检查每一行的条件。但似乎聚合函数只执行一次!

编辑 1

请也回答这个问题 仅在完成 ​​SELECT 语句后,INSERT 才会起作用。这就是为什么我没有得到预期的结果???我说的对吗?

【问题讨论】:

标签: sql sql-server sql-server-2008 tsql stored-procedures


【解决方案1】:

使用row_number 函数为您的行指定序号

insert into Table1 (column1,column2)
select 
    (select max(column1) from Table1) + row_number() over (order by T2.anotherColumn),
    T2.anotherColumn
from Table2 as T2

或更安全的版本(即使您在 Table1 中没有任何行也可以使用):

insert into Table1 (column1,column2)
select 
    isnull(T1.m, 0) + row_number() over (order by T2.anotherColumn),
    T2.anotherColumn
from Table2 as T2
    outer apply (select max(column) as m from Table1) as T1

【讨论】:

  • 仅在完成 ​​SELECT 语句后,INSERT 才会起作用。我对么?这就是为什么我没有得到预期的结果???
  • insert 用作插入一堆行,这就是为什么您的语句为所有行插入一个 column1,如果这就是您的意思
【解决方案2】:

我知道这个问题已经得到解答,但也许解决方案甚至可以进一步简化?怎么样

INSERT INTO TABLE1 (column1,column2)
SELECT ISNULL((SELECT MAX(column1) FROM TABLE1),0)
 +ROW_NUMBER() OVER (ORDER BY anotherColumn),
 anotherColumn FROM TABLE2

【讨论】:

    猜你喜欢
    • 2020-08-27
    • 2022-07-06
    • 2013-09-25
    • 2016-07-13
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 2019-02-24
    相关资源
    最近更新 更多