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_表名

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值