如何更改已经创建的表以删除并重新创建主键?

问题描述

我有这张桌子:

Create table Product (
    [Id] int primary key not null,[Name] varchar (250),[Price] money
)

该表已创建,现在我想用[Name]来使[Id]主键。

我不想重新创建表,而是只想ALTER

解决方法

error[E0599]: no method named `as_ref` found for struct `secp256k1::SecretKey` in the current scope --> src/main.rs:127:17 | 127 | let b = skey_b.as_ref(); | ^^^^^^ method not found in `secp256k1::SecretKey` | ::: /home/chris/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/src/libcore/convert/mod.rs:167:8 | 167 | fn as_ref(&self) -> &T; | ------ | | | the method is available for `std::boxed::Box<secp256k1::SecretKey>` here | the method is available for `std::sync::Arc<secp256k1::SecretKey>` here | the method is available for `std::rc::Rc<secp256k1::SecretKey>` here

,

您应始终明确命名约束。 由于您没有指定CONSTRAINT名称,因此SQL Server将为您的PK生成一个默认名称,例如:PK__Product__9CC368536561EF8B

因此,您需要使用SSMS或使用Dynamic SQL手动删除它,查询sys.key_constraints以获取名称并删除约束answered here

此外,您还需要在创建新PK之前将列Name设置为NOT NULL,并确保所有行(如果有的话)都不具有NULL值

ALTER TABLE Product ALTER COLUMN Name varchar (250) NOT NULL;

这是一个 db-fiddle

,

要修改主键,可以执行ALTER TABLE产品DROP PRIMARY KEY语句以删除现有的主键,然后执行ALTER TABLE ALTER column-name column-alteration语句为表设置新的主键

ALTER TABLE Product DROP PRIMARY KEY,ADD PRIMARY KEY(Id,Name);
,

我复制了您的问题以及解决方案...

在这里我找到您的表的主要名称

select CONSTRAINT_NAME 
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
where TABLE_NAME = 'Product' and CONSTRAINT_TYPE = 'PRIMARY KEY'

从上述查询中获取收益,并在下面的查询中替换(PK_ Product_ 3214EC07822AF903)

alter table Product drop constraint PK__Product__3214EC07822AF903

主键不能为空

alter table Product alter column [Name] varchar (250) NOT NULL

最后,设置新的主键

alter table Product add constraint PK_Product primary key ([Name])

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...