简体   繁体   English

如何使用SELECT INTO语句插入自动增量? SQL SERVER

[英]How to insert Auto-Increment using SELECT INTO Statement? SQL SERVER

This my table1: 这是我的表1:

Name        Description  
john        student       
dom         teacher

I need to use SELECT * INTO to transfer it to another table ( table2 ) but I want it with a new column named Auto which is auto-incremented . 我需要使用SELECT * INTO将它传输到另一个表( table2 ),但我想要一个名为Auto的新列,它是自动递增的

Which will look like this: 这将是这样的:

Name       Description        Auto
John        Student            1
Dom         Teacher            2

Current Code: SELECT * INTO table2 FROM table1 当前代码: SELECT * INTO table2 FROM table1

Use ROW_NUMBER to add sequential number starting from 1 . 使用ROW_NUMBER1开始添加序号。

SELECT *,
    Auto = ROW_NUMBER() OVER(ORDER BY(SELECT NULL))
INTO table2 
FROM table1

You can use an identity field for this, that's what they're for. 您可以使用标识字段,这就是它们的用途。 The logic of the identity(1,1) means that it will start at the number 1 and increment by 1 each time. 身份(1,1)的逻辑意味着它将从数字1开始并每次增加1。

Sample data; 样本数据;

CREATE TABLE #OriginalData (Name varchar(4), Description varchar(7))
INSERT INTO #OriginalData (Name, Description)
VALUES
('John','student')
,('Dom','teacher')

Make a new table and insert the data into it; 创建一个新表并将数据插入其中;

CREATE TABLE #NewTable (Name varchar(4), Description varchar(7), Auto int identity(1,1))
INSERT INTO #NewTable (Name, Description)
SELECT 
Name
,Description 
FROM #OriginalData

Gives the results as; 给出结果;

Name    Description Auto
John    student     1
Dom     teacher     2

If you ran the insert a couple more times your results would look like this; 如果你多次运行插入,你的结果会是这样的;

Name    Description Auto
John    student     1
Dom     teacher     2
John    student     3
Dom     teacher     4
John    student     5
Dom     teacher     6

The accepted answer has additional convenience when breaking one table into several smaller ones with the exact number of rows. 当将一个表分成具有确切行数的几个较小的表时,接受的答案具有额外的便利性。 If necessary, it is possible to remove the column used for autoincrement. 如有必要,可以去除用于自动增量的色谱柱。

SELECT *,
    ID = ROW_NUMBER() OVER(ORDER BY ( SELECT NULL ))
INTO #Table2
FROM Table1

DECLARE @start INT, @end INT;
SET @start = 1;
SET @end = 5000000;

SELECT *
INTO Table3
FROM #Table2
WHERE ID BETWEEN @start AND @end;

ALTER TABLE Table3 DROP COLUMN ID;       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM