一些数据库的基本操作

创建一个表

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值