How to use ALTER TABLE to add a new column and make it unique?

蓝咒 提交于 2019-12-06 23:56:21

问题


How do I use ALTER TABLE to add a new column and make it unique?


回答1:


Depends on the DBMS, but I think the following is quite portable:

ALTER TABLE table_name ADD column_name datatype
ALTER TABLE table_name ADD UNIQUE (column_name)

If you want to give a name to the UNIQUE constraint, you could replace the last command with this:

ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_name)



回答2:


if table is empty

  ALTER TABLE ADD (FieldName Type)
  ALTER TABLE ADD CONSTRAINT UNIQUE(FieldName)

If you have data in table you need to this in three steps:

  1. Add column
  2. Fill values
  3. Add unique constraint



回答3:


You can do it with a single SQL statement (at least with MySQL):

ALTER TABLE `people` ADD COLUMN `personal_code` VARCHAR(50) UNIQUE AFTER `surname`;



回答4:


It is a two step process: add the new coloumn, then add the constraint. Because UNIQUE constraints permit nulls it doesn't matter whether the table is populated:

SQL> select count(*) from t23
  2  /

  COUNT(*)
----------
         2


SQL> alter table t23
  2      add new_col number
  3  /

Table altered.

SQL> alter table t23
  2      add constraint t23_uk unique (new_col)
  3  /

Table altered.

SQL>


来源:https://stackoverflow.com/questions/3734891/how-to-use-alter-table-to-add-a-new-column-and-make-it-unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!