添加表字段
alter table table1 add transactor varchar(10) not Null;
alter table table1 add id int unsigned not Null auto_increment primary key
修改某個(gè)表的字段類(lèi)型及指定為空或非空
alter table 表名稱(chēng) change 字段名稱(chēng) 字段名稱(chēng) 字段類(lèi)型 [是否允許非空];
alter table 表名稱(chēng) modify 字段名稱(chēng) 字段類(lèi)型 [是否允許非空];
alter table 表名稱(chēng) modify 字段名稱(chēng) 字段類(lèi)型 [是否允許非空];
修改某個(gè)表的字段名稱(chēng)及指定為空或非空
alter table 表名稱(chēng) change 字段原名稱(chēng) 字段新名稱(chēng) 字段類(lèi)型 [是否允許非空
刪除某一字段
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語(yǔ)句塊如下:
22 declare @defname varchar(100)
declare @cmd varchar(500)
declare @tablename varchar(100)
declare @keyname varchar(100)
Set @tablename='Temp1'
Set @keyname='id' --需要設(shè)置的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)
如何取主鍵字段名稱(chēng)及字段類(lèi)型--得到主鍵字段名
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 字段序號(hào),k.keyno as 索引順序,t.name as 類(lèi)型
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='要查詢(xún)的表名'
and exists(select 1 from sysobjects where xtype = 'PK' and parent_obj=i.id and name = i.name)
order by o.name,k.colid
更多信息請(qǐng)查看IT技術(shù)專(zhuān)欄