Sql中用到的与表中的约束相关的操作
2011-04-06 09:50
302 查看
在SQL数据库中与表约束相关的操作
--查询表中所有的约束
exec sp_helpconstraint @objname=xt_hetong
go
添加主键约束
alter table 表名
add constraint 约束名 primary key (主键)
---添加唯一约束
alter table 表名
add constraint 约束名 unique (字段)
---添加默认约束
alter table 表名
add constraint 约束名 default ('默认内容') for 字段
--添加检查check约束,要求字段只能在1到100之间
alter table 表名
add constraint 约束名 check (字段 between 1 and 100 )
---添加外键约束(主表stuInfo和从表stuMarks建立关系,关联字段为stuNo)
alter table 从表
add constraint 约束名
foreign key(关联字段) references 主表(关联字段)
GO
--禁止所有表约束的SQL
select 'alter table '+name+' nocheck constraint all' from sysobjects where type='U'
--删除所有表数据的SQL
select 'TRUNCATE TABLE '+name from sysobjects where type='U'
--恢复所有表约束的SQL
select 'alter table '+name+' check constraint all' from sysobjects where type='U'
--删除某字段的约束
declare @name varchar(100)
--DF为约束名称前缀
select @name=b.name from syscolumns a,sysobjects b where a.id=object_id('表名') and b.id=a.cdefault and a.name='字段名' and b.name like 'DF%'
--删除约束
alter table 表明 drop constraint 约束名
--查询表中所有的约束
exec sp_helpconstraint @objname=xt_hetong
go
添加主键约束
alter table 表名
add constraint 约束名 primary key (主键)
---添加唯一约束
alter table 表名
add constraint 约束名 unique (字段)
---添加默认约束
alter table 表名
add constraint 约束名 default ('默认内容') for 字段
--添加检查check约束,要求字段只能在1到100之间
alter table 表名
add constraint 约束名 check (字段 between 1 and 100 )
---添加外键约束(主表stuInfo和从表stuMarks建立关系,关联字段为stuNo)
alter table 从表
add constraint 约束名
foreign key(关联字段) references 主表(关联字段)
GO
--禁止所有表约束的SQL
select 'alter table '+name+' nocheck constraint all' from sysobjects where type='U'
--删除所有表数据的SQL
select 'TRUNCATE TABLE '+name from sysobjects where type='U'
--恢复所有表约束的SQL
select 'alter table '+name+' check constraint all' from sysobjects where type='U'
--删除某字段的约束
declare @name varchar(100)
--DF为约束名称前缀
select @name=b.name from syscolumns a,sysobjects b where a.id=object_id('表名') and b.id=a.cdefault and a.name='字段名' and b.name like 'DF%'
--删除约束
alter table 表明 drop constraint 约束名
相关文章推荐
- Oracle SQL*PLUS与用户操作相关的常用命令
- Oracle:SQL语句--对表的操作——添加外键约束
- 数据统计例子,相关子查询!(SQL 中循环操作一列数据方法)
- Oracle PL\SQL操作(四)索引与约束
- SQL基础学习(三)- mySQL数据库相关操作
- sql 相关操作
- SQL Server 2005------表,列,约束,主键相关的实用T-SQL
- sql 增加键约束 删除主记录在其他表中的相关记录
- T-SQL约束操作
- 【C#属性理解】--与SQL交互用到的 【DataSet】相关
- 用到的与sql相关的总结
- MySQL数据表相关操作-完整性约束条件
- .NET + Excel + SQL 的导入导出相关操作
- sql中的关键字以及相关的一些操作(2)join(2)
- sql 增加键约束 删除主记录在其他表中的相关记录
- Statement接口以及Java相关SQL语句操作
- SQL 日期操作相关
- SQL Server 2005------表,列,约束,主键相关的实用T-SQL
- Sql 数据库的新建,表的新建,约束操作,简单查询
- mysql之sql语句-数据库、表结构相关的基础操作