从另一个表中插入sql server中的数据

时间:2015-02-08 14:25:57

标签: sql-server database

我在table_3中有一些记录,我想将该记录插入table_2,但第一列(Id)的值将是table_1的(NUMBER + 1)。我的代码是

INSERT INTO TABLE_2(Id,NAME)
SELECT (SELECT MAX(NUMBER) FROM TABLE_1)+1 AS Id,name
FROM TABLE_3

table_1的计数是200. TABLE_3的计数是10.我想要新插入的ID就像

(适用201,202,203,204,205,206,207,208,209,210)

但是从查询中得到的就像......

(适用201,201,201,201,201,201,201,201,201,201)

2 个答案:

答案 0 :(得分:2)

您只需使用only one select ROW_NUMBER()group by

即可完成此操作
INSERT INTO TABLE_2(Id,NAME)
 SELECT MAX(NUMBER) + ROW_NUMBER() OVER (ORDER BY name),name
 FROM TABLE_3
 group by name

答案 1 :(得分:1)

在您的查询(SELECT MAX(NUMBER) FROM TABLE_1)+1始终相同,因为MAX(NUMBER)只是200

如果要为插入的每个新记录增加1, (SELECT MAX(NUMBER) FROM TABLE_1)+1开始,请尝试以下操作:

INSERT INTO TABLE_2 (Id, NAME)
SELECT Id + rn, name 
FROM (
   SELECT (SELECT MAX(NUMBER) FROM TABLE_1) AS Id, name,
          ROW_NUMBER() OVER (ORDER BY name) AS rn
   FROM TABLE_3 ) t