postgresql 将主键设置为现有表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35571935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set primary key to existing table
提问by Adde.N
I have a table with 15 records. The table does not have any primary key constraint.
我有一张有 15 条记录的表。该表没有任何主键约束。
Now I want to set a primary key in the existing column. How can I set a column with primary key constraint to the existing table? Can somebody provide the query to alter the column?
现在我想在现有列中设置一个主键。如何将具有主键约束的列设置为现有表?有人可以提供查询来更改列吗?
It is for SQL server 2008.
它适用于 SQL Server 2008。
回答by yuvi
This is a runnable script. Try this:
这是一个可运行的脚本。试试这个:
IF NOT EXISTS(SELECT 'X'
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'PRIMARY_KEY_NAME'
AND TABLE_NAME = 'TABLE_NAME')
ALTER TABLE TABLE_NAME
ADD CONSTRAINT PRIMARY_KEY_NAME PRIMARY KEY(COLUMN_NAME_TO_BE_ADDED_AS_PRIMARY_KEY)
GO
回答by TheGameiswar
Setting the primary key is simple as in the below query, but column should be declared not null and if any existing values violate the primary key constraint, your query may not succeed.
设置主键很简单,就像下面的查询一样,但列应该声明为非空,如果任何现有值违反主键约束,您的查询可能不会成功。
create table
#temp
(
id int
)
ALTER TABLE #temp
ADD CONSTRAINT id_pk PRIMARY KEY (id)
The above will fail. You have to run the below query first at least in SQL Server 2005.
以上将失败。您必须至少在 SQL Server 2005 中首先运行以下查询。
alter table #temp
alter column id int not null
回答by Sankar
Alter syntax to add Primary Key Constraint to Existing Table...
更改语法以将主键约束添加到现有表...
ALTER TABLE table_name
ADD CONSTRAINT Primarykeyname PRIMARY KEY (column_name);
Specify the column name which one you want to set Primary Key. The values of the column should be unique.
指定要设置主键的列名。列的值应该是唯一的。