SQL:如何在INSERT INTO语句中继续在目标表中插入记录号

时间:2016-08-10 13:36:12

标签: sql-server

我有这样的查询:

 declare @guidd nvarchar(10)
        set @guidd = '11233'
        create table rrr_temp(value nvarchar(10), value2 int)
        create table rrr_tempA(valueA nvarchar(10), guidd nvarchar(10), ranks int)
        insert into rrr_temp values('AAA', 200)
        insert into rrr_temp values ('BBB', 400)
        insert into rrr_temp values ('CCC', 300)

        INSERT INTO rrr_tempA(valueA , guidd , ranks )
            SELECT RT.value, @guidd , row_number() over (order by (select NULL))
            FROM rrr_temp(nolock) RT
            INNER JOIN 
                (SELECT value, min(value2) AS lastLeg
                FROM rrr_temp(nolock) RTL               
                GROUP BY value) GrpRoute 
            ON RT.value = GrpRoute.value
            ORDER BY value2
            select * from rrr_tempA

使用上面的INSERT iNTO语句,我只能通过使用'row_number()over(order by(select NULL))'来插入Target表的'rank'列的源表(rrr_temp)的记录号。但是,我想在插入目标表时增加数字。我不能使用IDENTITY。感谢。

1 个答案:

答案 0 :(得分:0)

你在问这样的事吗?

select @max_rank = max(ranks)
from rrr_tempA

set @max_rank = IsNull(@max_rank, 0)

INSERT INTO rrr_tempA(valueA , guidd , ranks )
SELECT RT.value, @guidd , @max_rank + row_number() over (order by (select NULL))