Home  >  Article  >  Database  >  Mysql主键相关的sql语句集锦_MySQL

Mysql主键相关的sql语句集锦_MySQL

WBOY
WBOYOriginal
2016-06-01 13:05:55770browse

添加表字段

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('+@keyname+')'
   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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn