[英]Auto increment column in SQL server with select
Hello I am populating a table with data from a different table.您好,我正在使用来自不同表的数据填充表。 These are both pre-existing tables that have data in them.
这些都是预先存在的表,其中包含数据。 My script is almost working.
我的脚本几乎可以工作了。 It selects the appropriate values from the selection table and inserts the new record into the target table, but it is the ID column value that is problematic.
它从选择表中选择适当的值并将新记录插入到目标表中,但是有问题的是 ID 列值。 I need the ID value to auto-increment based on the previous row.
我需要 ID 值根据上一行自动递增。 Instead of auto incrementing based on the previous row which is at a value of 268564, the script places a 1 and auto-increment from there as in 1, 2, 3 etc. I need the new row's ID to be 268565. Please see below, thanks all.
脚本不是根据值为 268564 的前一行自动递增,而是从那里放置一个 1 并自动递增,如 1、2、3 等。我需要新行的 ID 为 268565。请参见下文,谢谢大家。
set identity_insert Table A ON;
INSERT INTO Table A
(ID, Field2, Field3, Field4, Field5)
SELECT ROW_NUMBER() OVER (ORDER BY Table A.[ID]) AS Number, Field2, Field3, 0, Field4, Field5
FROM Table B
LEFT JOIN Table A
ON Table A.[match] = Table B.[match]
WHERE
Table B.[match] = 44593
set identity_insert Table A OFF
ID ![]() |
Field1![]() |
Field2![]() |
Field3![]() |
Field4![]() |
---|---|---|---|---|
268564 ![]() |
table A value1![]() |
table A value2![]() |
table A value3![]() |
table A value4![]() |
1 ![]() |
table B value1![]() |
table B value2![]() |
table B value3![]() |
table B value4![]() |
Hello all thanks for your help.大家好,感谢您的帮助。 I was able to figure it out.
我能够弄清楚。 I needed to use
我需要使用
ROW_NUMBER() OVER (order by (select 1))+ (SELECT COALESCE(MAX(Table A.[ID]),0) FROM Table A)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.