SQL 目录:https://blog.youkuaiyun.com/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_表名