选择升序ID

时间:2016-09-29 09:45:20

标签: sql-server tsql

我想选择要插入的行并需要升序ID - 如何?

INSERT INTO myTable (ID, ColA, ColB)
SELECT (SELECT max(ID) + 1 FROM myTable), colA, colB FROM myOtherTable

不幸的是,这导致:

5, 'a1', 'b1'
5, 'a2', 'b2'
5, 'a3', 'b3'

我需要

5, ...
6, ...
7, ...

我可以使用一些常量而不是+1来提升ID吗?像+@ROWNUM ...

这样的东西

4 个答案:

答案 0 :(得分:0)

ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) AS IDSEQ

答案 1 :(得分:0)

找到最大值,我们可以增加值

Declare @i int;

    DECLARE @TABLEA  TABLE (PK INT,custno VARCHAR(10),cno VARCHAR(10))

    DECLARE @TABLEB  TABLE (PK INT,custno VARCHAR(10),cno VARCHAR(10))

    INSERT INTO @TABLEB (PK,custno,cno) VALUES (5,'a1','b1'),(5,'a2','b2'),(5,'a3','b3')
    Select @i = max(pk)  from @TABLEB;

    INSERT INTO @TABLEA (PK, custno,cno)
    Select @i + ROW_NUMBER() over(order by custno)   , CustNo,cno
    FROM @TABLEB

    SELECT * FROM @TABLEA

    SELECT * FROM @TABLEB

答案 2 :(得分:0)

您可以尝试这样,非常简单

SELECT (select MAX(ID) from table1)+row_number() OVER (ORDER BY col1, col2) ID,
       col1, 
       col2
  FROM table1

答案 3 :(得分:0)

我必须调整jimmy8ball的答案(删除PARTITION BY部分才能使其正常工作):

INSERT INTO myTable (ID, ColA, ColB)
SELECT (SELECT max(ID) FROM myTable) + x.rownum, x.colA, x.colB 
FROM (SELECT ROW_NUMBER() OVER (ORDER BY ID) FROM myOtherTable) x