我 常用 的 一些 sqlserver中 操作 表,字段和 索引 的sql 语句 ,post到这里,留作备忘录。 lastupdate: 2012-12-31 -- 创建表,带主键create table 新表名( [fid] [int] identity(1,1) not null, [fa] [int] null, [fb] [smallint] null, [fc] [tinyint] n
我常用的一些sqlserver中操作表,字段和索引的sql语句,post到这里,留作备忘录。
lastupdate: 2012-12-31
-- 创建表,带主键create table 新表名( [fid] [int] identity(1,1) not null, [fa] [int] null, [fb] [smallint] null, [fc] [tinyint] null, [fd] [varchar] (60) null, [fe] [nvarchar] (60) null, [ff] [varbinary] (60) null, constraint 主键名 primary key clustered ( [fid] asc )with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary] ) on [primary]-- 删除表drop table 表名-- 字段改名exec sp_rename '表名.旧字段名', '新字段名', 'column'-- 修改字段类型alter table 表名 alter column 字段名 int not nullalter table 表名 alter column 字段名 varchar(60)-- 添加字段-- 63 63 72 75 6e 2e 63 6f 6dalter table 表名 add 字段名 int identity(1,1) -- 添加自增字段alter table 表名 add 字段名 nvarchar(60)alter table 表名 add 字段名 smallint-- 删除字段alter table 表名 drop column 字段名-- 添加主键alter table 表名 add constraint 主键名 primary key(字段名)alter table 表名 add constraint 主键名 primary key(字段1,字段2,字段3)-- 设置主键不能为空alter table 表名 alter column 主键名 not null-- 删除主键alter table 表名 drop 主键名-- 创建索引create index 索引名 on 表名(字段名)create index 索引名 on 表名(字段1,字段2,字段3)-- 删除索引drop index 索引名 on 表名-- 随机筛选记录select 字段1,字段2 from 表名 where 条件 order by newid()-- 查看sqlserver中各表占用大小情况exec sp_msforeachtable exec sp_spaceused '?'-- 重建索引dbcc dbreindex('表名')dbcc dbreindex('表名', '索引名')dbcc dbreindex('表名', '索引名', 90)-- 查某一列(或多列)的重复值(只能查出重复记录的值,不能整个记录的信息)-- 如: 查找 字段1,字段2 重复的记录select 字段1,字段2 from 表名 group by 字段1,字段2 having(count(*))>1 -- 查某一列有重复值的记录(这种方法查出的是所有重复的记录,也就是说如果有两条记录重复的,就查出两条)-- 如: 查找 字段1 重复的记录select * from 表名 where 字段1 in (select 字段1 from 表名 group by 字段1 having(count(*))>1) -- 查某一列有重复值的记录(只显示多余的记录,也就是说如果有三条记录重复的,就显示两条)-- 这种方成绩的前提是:需有一个不重复的列,本例中的是字段2,以下是查找 字段1 重复的记录select * from 表名 t1 where 字段2 not in (select max(字段2) from 表名 t2 where t1.字段1=t2.字段1)-- 用随机值填充某字段 (60以内的数字)update 表名 set 字段 = cast(ceiling(rand(checksum(newid())) * 60) as int)-- 增加约束alter table 表名 add constraint [df_表名_字段名] default ('默认值') for [字段名] -- ((0))-- 删除约束alter table 表名 drop constraint 约束名 -- 查询约束名select c.name from sysconstraints a inner join syscolumns b on a.colid=b.colid inner join sysobjects c on a.constid=c.id where a.id=object_id('表名') and b.name='字段名'
