现在的位置: 首页 > 综合 > 正文

一些简单、基础的SQL语句

2013年03月02日 ⁄ 综合 ⁄ 共 1229字 ⁄ 字号 评论关闭

创建数据库

create database data

 

切换数据库

use data

 

创建基本表

create table Class (Clno char(5) not null primary key
,Speciality varchar(20) not null
,Inyear char(4) not null
,Number integer
,Monitor char(7))

 

为已经创建好的表设置主键

alter table Course add primary key(Cno)

 

为现有表增加属性
alter table Student add Nation Varchar(20)

 

删除现有表某条属性

alter table Student drop column Nation

 

插入记录

insert into Grade values('2001110','3',80)

 

按条件更新记录

update Grade set Gmark=70 where Sno='2001110'

 

删除特定记录

delete from Grade where Sno='2001110'

 

创建视图

create index IX_Class on Student(Clno)

 

1)禁止所有表约束的SQL
select 'alter table '+name+' nocheck constraint all' from sysobjects where type='U'

2)删除所有表数据的SQL
select 'TRUNCATE TABLE '+name from sysobjects where type='U'

3)恢复所有表约束的SQL
select 'alter table '+name+' check constraint all' from sysobjects where type='U'

4)删除某字段的约束
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 @name
--为字段添加新默认值和约束
ALTER TABLE 表名 ADD CONSTRAINT @name  DEFAULT (0) FOR [字段名] 对字段约束进行更改
--删除约束
ALTER TABLE tablename
Drop CONSTRAINT 约束名
--修改表中已经存在的列的属性(不包括约束,但可以为主键或递增或唯一)
ALTER TABLE tablename
alter column 列名 int not null
--添加列的约束
ALTER TABLE tablename
ADD CONSTRAINT DF_tablename_列名 DEFAULT(0) FOR 列名
--添加范围约束
alter table   tablename  add  check(性别 in ('M','F'))

抱歉!评论已关闭.