SQL Serverデータベーステーブルへのプライマリ・キー列の追加


SQLディレクトリ:https://blog.csdn.net/dkbnull/article/details/87932858
 
SQL Serverデータベースで、プライマリ・キーが設定されているデータベース・テーブルに新しい列を挿入し、プライマリ・キーを設定します.
まず基礎知識から見て、
テーブルの作成:
create table    ( 
      1 int not null,    …………,
   [constraint    ] primary key (   1, …)
)

既存のテーブルにプライマリ・キー制約を追加
alter table    [add constraint    ] primary key(   1 ,… )

プライマリ・キーの削除
alert table    drop constraint    

SQL Serverデータベースで、プライマリ・キーが設定されているデータベース・テーブルに新しい列を挿入し、プライマリ・キーを設定します.
SQL文は次のとおりです.
if not exists (select 1 from syscolumns where name = '   1' and id = (select id from sysobjects where name = '  ' and type = 'U')) 
begin 
  alter table    add    1 varchar(4) NOT NULL default '0';
  alter table    drop constraint    ; 	
  alter table    add constraint     primary key (   1,    2,    3);
end

コンストレイント名は一般的にPK_と命名されます.テーブル名