SQL Server 为现有表添加自增主键

发布于 2024-10-15 01:20:46 字数 129 浏览 3 评论 0原文

如标题所示,我有一个现有表,其中已填充 150000 条记录。我添加了一个 Id 列(当前为空)。

我假设我可以运行一个查询来用增量数字填充此列,然后设置为主键并打开自动增量。这是正确的方法吗?如果是这样,我该如何填写初始数字?

As the title, I have an existing table which is already populated with 150000 records. I have added an Id column (which is currently null).

I'm assuming I can run a query to fill this column with incremental numbers, and then set as primary key and turn on auto increment. Is this the correct way to proceed? And if so, how do I fill the initial numbers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

甜味拾荒者 2024-10-22 01:20:47

此答案是对最高投票答案的一个小补充,适用于 SQL Server。问题要求自动增量主键,当前答案确实添加了主键,但没有标记为自动增量。下面的脚本检查列是否存在,并在启用自动增量标志的情况下添加它。

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTable' AND COLUMN_NAME = 'PKColumnName')
BEGIN


ALTER TABLE dbo.YourTable
   ADD PKColumnName INT IDENTITY(1,1)

CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED

END

GO

This answer is a small addition to the highest voted answer and works for SQL Server. The question requested an auto increment primary key, the current answer does add the primary key, but it is not flagged as auto-increment. The script below checks for the columns, existence, and adds it with the autoincrement flag enabled.

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTable' AND COLUMN_NAME = 'PKColumnName')
BEGIN


ALTER TABLE dbo.YourTable
   ADD PKColumnName INT IDENTITY(1,1)

CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED

END

GO
总以为 2024-10-22 01:20:47
ALTER TABLE table_name ADD temp_col INT IDENTITY(1,1) 
update 
ALTER TABLE table_name ADD temp_col INT IDENTITY(1,1) 
update 
夜雨飘雪 2024-10-22 01:20:47

由设计师您可以设置身份 (1,1)
右键单击表 =>设计=>部分左侧(右键单击)=>属性=>在身份列中选择 #column

属性

身份栏

by the designer you could set identity (1,1)
right click on tbl => desing => in part left (right click) => properties => in identity columns select #column

Properties

idendtity column

已下线请稍等 2024-10-22 01:20:47

如果您的表使用其主键或 foriegen 键与其他表有关系,则可能无法更改您的表。因此您需要删除并再次创建表。
要解决这些问题,您需要通过右键单击数据库来生成脚本,并在高级选项中设置数据类型以编写方案和数据的脚本。之后,使用此脚本更改您的列,以通过运行其查询来识别和重新生成表。
您的查询将如下所示:

USE [Db_YourDbName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Drop TABLE [dbo].[Tbl_TourTable]

CREATE TABLE [dbo].[Tbl_TourTable](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NULL,
    [Family] [nvarchar](150) NULL)  

GO

SET IDENTITY_INSERT [dbo].[Tbl_TourTable] ON 

INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')

SET IDENTITY_INSERT [dbo].[Tbl_TourTable] off 

If your table has relationship with other tables using its primary or foriegen key, may be it is impossible to alter your table. so you need to drop and create the table again.
To solve these problems you need to Generate Scripts by right click on the database and in advanced option set type of data to script to scheme and data. after that, using this script with the changing your column to identify and regenerate the table using run its query.
your query will be like here:

USE [Db_YourDbName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Drop TABLE [dbo].[Tbl_TourTable]

CREATE TABLE [dbo].[Tbl_TourTable](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NULL,
    [Family] [nvarchar](150) NULL)  

GO

SET IDENTITY_INSERT [dbo].[Tbl_TourTable] ON 

INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')
INSERT [dbo].[Tbl_TourTable] ([ID], [Name], [Family]) VALUES (1,'name 1', 'family 1')

SET IDENTITY_INSERT [dbo].[Tbl_TourTable] off 
瞳孔里扚悲伤 2024-10-22 01:20:47

我看到一个解决方案不久前已被接受,但我想我应该添加另一种方法,因为我处于类似的位置。

接受的解决方案更简单,但不提供控制排序的能力(就像我的情况一样保留日期时间列的时间顺序)。

在 SQL Server 中,我的解决方案是:

  1. 从旧表中的条目创建一个新表(以便我可以指定排序),包括新的编号列
  2. 将新的编号列设置为主键
  3. 删除旧表
  4. 重命名新表

代码:

SELECT IDENTITY(INT, 1, 1) AS id, OldTable.*
INTO TempOldTable
FROM OldTable
ORDER BY OldTable.start_time;

-- set new numbered column as primary key
ALTER TABLE TempOldTable
ADD CONSTRAINT PK_TempOldTable PRIMARY KEY (id);

-- Optionally, verify new table data
-- SELECT * FROM TempOldTable;

DROP TABLE OldTable;

--rename new table
EXEC sp_rename 'TempOldTable', 'OldTable';

<强>完全披露:我通过一些积极的研究(这篇文章有所帮助)和对 ChatGPT 的一些询问得出了这个解决方案。

I see a solution to this was accepted a while ago, but I thought I'd add another approach since I'm in a similar position.

The accepted solution is simpler, but does not offer the ability to control the ordering (like preserving chronological ordering of a datetime column as is my case).

In SQL Server, my solution was to:

  1. create a new table from entries in the old (so that I could specify ordering) including the new numbered column
  2. set the new numbered column as primary key
  3. drop the old table
  4. rename the new table

Code:

SELECT IDENTITY(INT, 1, 1) AS id, OldTable.*
INTO TempOldTable
FROM OldTable
ORDER BY OldTable.start_time;

-- set new numbered column as primary key
ALTER TABLE TempOldTable
ADD CONSTRAINT PK_TempOldTable PRIMARY KEY (id);

-- Optionally, verify new table data
-- SELECT * FROM TempOldTable;

DROP TABLE OldTable;

--rename new table
EXEC sp_rename 'TempOldTable', 'OldTable';

Full disclosure: I arrived at this solution through some active researching (this post helped), and some interrogation of ChatGPT.

雪化雨蝶 2024-10-22 01:20:47

这是一个你可以尝试的想法。
原始表 - 无标识列 table1
创建一个新表 - 调用 table2 以及标识列。
将数据从 table1 复制到 table2 - 标识列会自动填充自动递增的数字。

将原始表 - table1 重命名为 table3
将新表 - table2 重命名为 table1(原始表)
现在您已经拥有包含标识列并为现有数据填充的 table1。
确保没有问题并正常工作后,在不再需要时删除 table3。

Here is an idea you can try.
Original table - no identity column table1
create a new table - call table2 along with identity column.
copy the data from table1 to table2 - the identity column is populated automatically with auto incremented numbers.

rename the original table - table1 to table3
rename the new table - table2 to table1 (original table)
Now you have the table1 with identity column included and populated for the existing data.
after making sure there is no issue and working properly, drop the table3 when no longer needed.

最丧也最甜 2024-10-22 01:20:47

创建一个具有不同名称和相同列、主键和外键关联的新表,并将其链接到代码的 Insert 语句中。
例如:对于 EMPLOYEE,请替换为 EMPLOYEES。

CREATE TABLE EMPLOYEES(

    EmpId        INT NOT NULL IDENTITY(1,1), 
    F_Name       VARCHAR(20) ,
    L_Name       VARCHAR(20) ,
    DOB          DATE ,
    DOJ          DATE ,
    PRIMARY KEY (EmpId),
    DeptId int FOREIGN KEY REFERENCES DEPARTMENT(DeptId),
    DesgId int FOREIGN KEY REFERENCES DESIGNATION(DesgId),
    AddId int FOREIGN KEY REFERENCES ADDRESS(AddId)   
) 

但是,您必须删除现有的 EMPLOYEE 表或根据您的要求进行一些调整。

Create a new Table With Different name and same columns, Primary Key and Foreign Key association and link this in your Insert statement of code.
For E.g : For EMPLOYEE, replace with EMPLOYEES.

CREATE TABLE EMPLOYEES(

    EmpId        INT NOT NULL IDENTITY(1,1), 
    F_Name       VARCHAR(20) ,
    L_Name       VARCHAR(20) ,
    DOB          DATE ,
    DOJ          DATE ,
    PRIMARY KEY (EmpId),
    DeptId int FOREIGN KEY REFERENCES DEPARTMENT(DeptId),
    DesgId int FOREIGN KEY REFERENCES DESIGNATION(DesgId),
    AddId int FOREIGN KEY REFERENCES ADDRESS(AddId)   
) 

However, you have to either delete the existing EMPLOYEE Table or do some adjustment according to your requirement.

箹锭⒈辈孓 2024-10-22 01:20:47

alter table /** 粘贴 tabal 的名称 **/
add id int IDENTITY(1,1)

delete from /** 粘贴选项卡的名称 **/
where id in

(

select a.id FROM /** 将选项卡的名称 / 粘贴为
左外连接 (
选择 MIN(id) 作为 id
FROM /
粘贴选项卡的名称/
分组依据
/
粘贴列 c1,c2 .... **/

) as t1 
ON a.id = t1.id

WHERE t1.id IS NULL

)

alter table /** 粘贴 tabal 的名称 **/
删除列 ID

alter table /** paste the tabal's name **/
add id int IDENTITY(1,1)

delete from /** paste the tabal's name **/
where id in

(

select a.id FROM /** paste the tabal's name / as a
LEFT OUTER JOIN (
SELECT MIN(id) as id
FROM /
paste the tabal's name /
GROUP BY
/
paste the columns c1,c2 .... **/

) as t1 
ON a.id = t1.id

WHERE t1.id IS NULL

)

alter table /** paste the tabal's name **/
DROP COLUMN id

☆獨立☆ 2024-10-22 01:20:47

试试下面的代码:

DBCC CHECKIDENT ('settings', RESEED, 0) 

Try This Code Bellow:

DBCC CHECKIDENT ('settings', RESEED, 0) 
与君绝 2024-10-22 01:20:47

这在 MariaDB 中有效,所以我只能希望它在 SQL Server 中也有效:删除刚刚插入的 ID 列,然后使用以下语法:-

ALTER TABLE table_name ADD id INT PRIMARY KEY AUTO_INCREMENT;

不需要另一个表。这只是插入一个 id 列,使其成为主索引,并用顺序值填充它。如果 SQL Server 不这样做,我很抱歉浪费了您的时间。

This works in MariaDB, so I can only hope it does in SQL Server: drop the ID column you've just inserted, then use the following syntax:-

ALTER TABLE table_name ADD id INT PRIMARY KEY AUTO_INCREMENT;

No need for another table. This simply inserts an id column, makes it the primary index, and populates it with sequential values. If SQL Server won't do this, my apologies for wasting your time.

下壹個目標 2024-10-22 01:20:47

尝试这样的事情(首先在测试台上):

USE your_database_name
GO
WHILE (SELECT COUNT(*) FROM your_table WHERE your_id_field IS NULL) > 0
BEGIN
    SET ROWCOUNT 1
    UPDATE your_table SET your_id_field = MAX(your_id_field)+1
END
PRINT 'ALL DONE'

我根本没有测试过这个,所以要小心!

Try something like this (on a test table first):

USE your_database_name
GO
WHILE (SELECT COUNT(*) FROM your_table WHERE your_id_field IS NULL) > 0
BEGIN
    SET ROWCOUNT 1
    UPDATE your_table SET your_id_field = MAX(your_id_field)+1
END
PRINT 'ALL DONE'

I have not tested this at all, so be careful!

世界如花海般美丽 2024-10-22 01:20:47
ALTER TABLE table_name ADD COLUMN ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT ;

这可能有用

ALTER TABLE table_name ADD COLUMN ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT ;

This could be useful

痴骨ら 2024-10-22 01:20:46

不 - 您必须以相反的方式执行此操作:从一开始就将其添加为 INT IDENTITY - 当您执行此操作时,它将填充身份值:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY

然后您可以将其设为主要关键:

ALTER TABLE dbo.YourTable
   ADD CONSTRAINT PK_YourTable
   PRIMARY KEY(ID)

或者如果您喜欢一步完成所有操作:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY
       CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED

No - you have to do it the other way around: add it right from the get go as INT IDENTITY - it will be filled with identity values when you do this:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY

and then you can make it the primary key:

ALTER TABLE dbo.YourTable
   ADD CONSTRAINT PK_YourTable
   PRIMARY KEY(ID)

or if you prefer to do all in one step:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY
       CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED
浅唱ヾ落雨殇 2024-10-22 01:20:46

您无法“打开”IDENTITY:这是表重建。

如果您不关心数字顺序,则可以一次性添加带有 IDENTITY 的 NOT NULL 列。 150k 行并不是很多。

如果您需要保留某些数字顺序,请相应地添加数字。然后使用 SSMS 表设计器设置 IDENTITY 属性。这允许您生成一个脚本,该脚本将为您执行列删除/添加/保留数字/重新设定种子。

You can't "turn on" the IDENTITY: it's a table rebuild.

If you don't care about the number order, you'd add the column, NOT NULL, with IDENTITY in one go. 150k rows isn't a lot.

If you need to preserve some number order, then add the numbers accordingly. Then use the SSMS table designer to set the IDENTITY property. This allows you to generate a script which will do the column drop/add/keep numbers/reseed for you.

挽心 2024-10-22 01:20:46

我遇到了这个问题,但无法使用身份列(由于各种原因)。
我决定这样做:

DECLARE @id INT
SET @id = 0 
UPDATE table SET @id = id = @id + 1 

借用 此处

I had this issue, but couldn't use an identity column (for various reasons).
I settled on this:

DECLARE @id INT
SET @id = 0 
UPDATE table SET @id = id = @id + 1 

Borrowed from here.

摘星┃星的人 2024-10-22 01:20:46

如果该列已存在于表中且为空,则可以使用以下命令更新该列(替换 id、tablename 和 tablekey ):

UPDATE x
SET x.<Id> = x.New_Id
FROM (
  SELECT <Id>, ROW_NUMBER() OVER (ORDER BY <tablekey>) AS New_Id
  FROM <tablename>
  ) x

If the column already exists in your table and it is null, you can update the column with this command (replace id, tablename, and tablekey ):

UPDATE x
SET x.<Id> = x.New_Id
FROM (
  SELECT <Id>, ROW_NUMBER() OVER (ORDER BY <tablekey>) AS New_Id
  FROM <tablename>
  ) x
謸气贵蔟 2024-10-22 01:20:46

当我们在现有表中添加标识列时,它将自动填充,无需手动填充。

When we add and identity column in an existing table it will automatically populate no need to populate it manually.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文