当前位置: 移动技术网 > IT编程>数据库>Mysql > Mysql主键相关的sql语句集锦

Mysql主键相关的sql语句集锦

2017年12月12日  | 移动技术网IT编程  | 我要评论

添加表字段

alter table table1 add transactor varchar(10) not null;

alter table   table1 add id int unsigned not null auto_increment primary key

修改某个表的字段类型及指定为空或非空

alter table 表名称 change 字段名称 字段名称 字段类型 [是否允许非空];

alter table 表名称 modify 字段名称 字段类型 [是否允许非空];

alter table 表名称 modify 字段名称 字段类型 [是否允许非空];

修改某个表的字段名称及指定为空或非空

alter table 表名称 change 字段原名称 字段新名称 字段类型 [是否允许非空

删除某一字段

alter table mytable drop 字段 名;

添加唯一键

alter table `test2` add unique ( `userid`)

修改主键

alter table `test2` drop primary key ,add primary key ( `id` )

增加索引

alter table `test2` add index ( `id` )

alter table `category ` modify column `id`  int(11) not null auto_increment first ,add primary key (`id`);

修改主键的sql语句块如下:

22 declare @defname varchar(100)
declare @cmd varchar(500)
declare @tablename varchar(100)
declare @keyname varchar(100)
set @tablename='temp1'
set @keyname='id' --需要設置的key,分隔
select @defname= name
   from sysobjects so
   join sysconstraints sc
   on so.id = sc.constid
   where object_name(so.parent_obj) = @tablename
   and xtype='pk'
if @defname is not null
begin
select @cmd='alter table '+ @tablename+ ' drop constraint '+ @defname
--print @cmd
   exec (@cmd)
 end
else
 set @defname='pk_'+@keyname
select @cmd='alter table '+ @tablename+ ' add constraint '+ @defname +' primary key clustered(
   exec (@cmd)

  如何取主键字段名称及字段类型--得到主键字段名

1:
select table_name,column_name from information_schema.key_column_usage

where table_name<>'dtproperties'

2:
exec sp_pkeys @table_name='表名'

3:
select o.name as 表名,c.name as 字段名,k.colid as 字段序号,k.keyno as 索引顺序,t.name as 类型

from sysindexes i

join sysindexkeys k on i.id = k.id and i.indid = k.indid

join sysobjects o on i.id = o.id

join syscolumns c on i.id=c.id and k.colid = c.colid

join systypes t on c.xusertype=t.xusertype

where o.xtype = 'u' and o.name='要查询的表名'

and exists(select 1 from sysobjects where xtype = 'pk' and parent_obj=i.id and name = i.name)

order by o.name,k.colid

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网