sqlserver基础操作

来源:互联网 发布:重庆鸿巨网络怎么样 编辑:程序博客网 时间:2024/06/18 15:36

启动服务:

1.在系统服务启动

2.在sql配置管理器服务选项中启动

3.在管理员cmd:net start mssqlserver;net stop mssqlserver

use mastergoif(not exists(select* from sysdatabases where name='school'))create database schoolon primary(name='School_data',filename='E:\School_data.mdf',size=10MB,filegrowth=1MB)log on(name='School_log',filename='E:\School_log.ldf',size=2MB,filegrowth=1MB)gouse schoolcreate table class(clId int not null identity(1,1) constraint PK_cid primary key,clName varchar(40) not null);//定义自增长主键create table student(stuId int not null identity(1,1)constraint PK_sid primary key,stuName varchar(20) not null,sex varchar check (sex in('F','M')) not null,clID int constraint FK_StuClass foreign key(clID) references class(clID)) //定义外键约束,检查约束insert into class(clName) values('软件1班')insert into class(clName) values('软件2班')insert into class(clName) values('软件2班')update class set clName='软件3班' where clId=3insert into class(clName) values('软件4班')select *from classinsert into student(stuName,sex,clID) values('用户1','F',1)insert into student(stuName,sex,clID) values('用户2','M',2)insert into student(stuName,sex,clID) values('用户3','F',3)insert into student(stuName,sex,clID) values('用户4','M',2)insert into student(stuName,sex) values('用户5','M')select *from student//内连接select student.clID,stuName,clName from studentinner join class on student.clId=class.clId order by clId//左连接select student.clID,stuName,clName from studentleft join class on student.clId=class.clIdwhere student.clId is null order by clId//右连接select count(student.clID)as count from studentright join class on student.clId=class.clIdgroup by class.clId having count(student.clID)>1//嵌套查询select *from student where clId=(select clId from class where clId=2)gouse mastergoif exists(select *from sysdatabases where name='school')drop database schooluse mastergoexec sp_detach_db schoolgoexec sp_attach_db school,'E:\School_data.mdf','E:\School_log.ldf'go


use master;


select *from spt_values order by number;//默认递增


select type,count(type) from spt_values group by type having count(type)>19;

select distinct type from spt_values;


create database hh;
use hh;


drop table ggz;
create table ggz(id int IDENTITY(1,1),num int not null,adds varchar(10))

//添加主键约束
alter table ggz alter column id int not null;
alter table ggz add constraint pk_id primary key(id);

//删除主键约束
alter table ggz drop constraint pk_id;

//添加唯一约束
alter table ggz add constraint UQ_adds unique(adds);

//添加默认约束
alter table ggz add constraint DF_adds default('ca') for adds;

//修改属性
alter table ggz alter column adds varchar(10) null;

//插入
insert into ggz(id,num) values(3,3);

//添加检查约束
alter table ggz add constraint CK_num check(num in(1,0));

//更新
update ggz set num=2 where id=3;


insert into ggz(num) values(0);

//删除
delete from ggz where num=0;


0 0