创建一个表
create table Test
(
UserId int not null,
UserName nvarchar(50) not null
)
增加一个字段
alter table Test add Password nvarchar(100) not null -- 非空
alter table Test add Address nvarchr(1000)---可空
修改一个字段
alter table Test alter column Password nvarchar(200) not null
alter table Test alter column Password nvarchar(Max) not null
将一个不是自增的字段修改为自增字段
alter table Test drop column Id
alter table Test Add id int identity(1,1)
删除一个字段
alter table Test drop column Address
创建约束
alter table Test with check add constraint constraintName foreign key UserId
references OtherTableName UserId
on update cascade --这个逻辑有点问题,应该是Test表的UserId是OtherTableName的外键,当这个
on delete cascade --主键表的记录删除时,Test表的记录删除,
删除约束
alter table Test drop constraint constraintName
删除表
drop table Test
判断一个表是否存在
if exists (select * from sysobjects where id=object_id('tableName'))
print' exists'
else
print 'not exists'
判断一个字段是否存在
if exists(select * from syscolumns where id=object_id("tableName") and name="FieldName")
print 'exists'
else
print 'not exists'
判断一条记录是否存在
if exists(select * from Test where UserName ='admin')
begin
print 'exists'
print ' this is ok'
end
else
begin
print' not exists'
print 'please add the record'
end
sql语句延迟1秒钟
WAITFOR deplay '00:00:01'
创建聚集索引
create clustered index test_1 on Test_Customer(
Id desc
)
创建非聚集索引
create nonclustered index test_2 on Test_Customer
(
wage desc
)
重新生成索引
alter index test_1 on Test_Customer
rebuild
重新组织索引
alter idnex test_2 on Test_Customer
reorganize
删除索引
drop index test_1 on Test_Customer
在数据库表里Id字段设置为自增的时候不允许插入Id,
set Identity_insert test on --允许插入
set identity_insert test off -- 恢复不允许插入Id