SQL Server 2005------表,列,约束,主键相关的实用T-SQL

    技术2022-05-20  70

    1. 创建表   create table Student(StudentOID varchar(50), Age integer)  //表是可以没有主键的

    2. 创建表时指定主键   create table MyCustomer (CustomerID int Identity(100,1) Primary Key,CompanyName nvarchar(50))   //设置主键后,在控制台上"Keys","Indexs"节点下,默认出现一个Item,名称又系统自动生成。也就是说,主键自动对应一个聚簇索引   //主键是一种特殊的约束,但是在"Constraint"节点下是无法看到主键Item的

    3.  删除主键索引   drop index MyCustomer.PK__MyCustomer__014935CB  //失败,因为Index Object正在使用它   alter table MyCustomer drop Constraint PK__MyCustomer__014935CB //成功,主键被全部删除,但是主键列还是存在的   4. 对某存在的列,指定其为主键    alter table MyCustomer ADD CONSTRAINT PK_MyCustomer PRIMARY KEY CLUSTERED  ( OID ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

    5. 在某个列上添加Unique约束    alter table MyCustomer add CompanyOwnerName nvarchar(10) Constraint Unq_CompanyOwnerName Unique  //类似于主键,在控制台上"Keys","Indexs"节点下,默认出现一个Item,Unique约束自动创建一个非聚簇索引  //删除时,类似于删除主键所以操作

    6. 为某列添加Default约束  alter table MyCustomer add Constraint Def_CustomerAddress default 'Shanghai' for CustomerAddress //在"Constraint"节点下,出现一个Item,该约束一个列只能有一个

    7. 为某列添加Check约束  alter table MyCustomer add Constraint Chk_AddressValue check(CustomerAddress!='ssfd') //在"Constraint"节点下,出现一个Item

    8. 删除约束  alter table MyCustomer drop Constraint PL_OID

    9. 删除列  alter table MyCustomer drop column CustomerAddress  //必须保证没有其他对象,如该列上的约束存在,否则操作失败

    10.修改列的定义  alter table MyCustomer alter column CustomerAddress nvarchar(500) null //如果列数据类型改变了,而且有这个列上的约束有冲突,那么修改失败

    11.Check约束和Default约束都可以改名,但是后者的改名需要Refresh才可以在UI上看得到

    12. select * from sys.default_constraints  //查看所有Default约束     select * from sys.key_constraints       //查看所有Primary Key, Unique约束

    13. exec sp_helpconstraint MyCustomer     exec sp_helpindex  MyCustomer     exec sp_help  MyCustomer    //查看表范围内的约束,索引,表信息


    最新回复(0)