gpt4 book ai didi

sql-server - 在SQL表中添加主键列

转载 作者:行者123 更新时间:2023-12-02 02:30:27 25 4
gpt4 key购买 nike

我是 RDBMS 的学生。

我有一个非常基本的问题,假设我在 SQL Server 中有一个现有表。更改表的脚本是什么。

  • 删除列“RowId”(如果存在)。
  • 删除约束(如果存在)。
  • 向表中添加一个新列“RowId”。
  • 将此列设为主键。
  • 自动增量类型 int。

最佳答案

在 SQL Server 2005 或更高版本中,您可以使用此脚本:

-- drop PK constraint if it exists
IF EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID('dbo.YourTable') AND Name = 'PK_YourTable')
ALTER TABLE dbo.YourTable
DROP CONSTRAINT PK_YourTable
GO

-- drop column if it already exists
IF EXISTS (SELECT * FROM sys.columns WHERE Name = 'RowId' AND object_id = OBJECT_ID('dbo.YourTable'))
ALTER TABLE dbo.YourTable DROP COLUMN RowId
GO

-- add new "RowId" column, make it IDENTITY (= auto-incrementing)
ALTER TABLE dbo.YourTable
ADD RowId INT IDENTITY(1,1)
GO

-- add new primary key constraint on new column
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable
PRIMARY KEY CLUSTERED (RowId)
GO

当然,如果其他表使用预先存在的 RowId 列上的外键约束来引用此 dbo.YourTable,则此脚本可能仍会失败...

更新:当然,在我使用 dbo.YourTablePK_YourTable 的任何地方,您都必须替换那些带有来自您自己的数据库的实际表/约束名称的占位符(您在问题中没有提到它们是什么......)

关于sql-server - 在SQL表中添加主键列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9158564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com