SQL server基本使用示例一

来源:互联网 发布:刺客信条战斗力知乎 编辑:程序博客网 时间:2024/06/07 21:53

/创建数据库方法一/
create database Test1
on primary
(/以下是主数据文件的属性/
name =’Test1’,–主数据文件的逻辑名称
filename=’F:\Users\SQL Test\Test1.mdf’,–主数据文件的物理位置
size=5mb,–主数据文件的初试大小
maxsize=unlimited,–主数据文件的最大值
filegrowth=10% –主数据文件的增长率
),
(/* 以下是次要数据文件的属性*/
name=’Test1_a.ndf’,–次要数据文件的逻辑名称
filename=’F:\Users\SQL Test\Test1_a.ndf’,–次要数据文件的物理位置
size=3mb,–次要数据文件的初试大小
filegrowth=10% –次要数据文件的增长率
)
log on(
/* 以下是日志文件的属性*/
name=’Test1_log’,–日志文件的逻辑名称
filename=’F:\Users\SQL Test\Test1_log.ldf’,–日志文件的物理路径
size=1mb, –日志文件初始大小
filegrowth=2mb –日志文件增长率
)
go

/创建数据库方法二/
–创建数据库
create database Test1

–删除数据库
drop database Test1

use Test1
Go
/检测是否存在Authors/
if exists (select * from sysobjects where name=’Authors’)
drop table Authors
go
/创建作者表/
create table Authors(
AuthorID int not null identity(101,1) primary key,–编号 设置主键约束并自增,初始值为101,自赠数为1
AuthorName nvarchar(40) not null,–作者姓名
Sex bit not null default 1,–性别 设置默认约束,默认为男或女
Birthday datetime null,–生日
Age int, –年龄
Email nvarchar(50) default ‘e@books.com’ check (Email like ‘%@%’),–电子邮箱 设置默认邮箱为e@books.com,并设置检查约束,鉴定是否为邮箱
TelPhone nvarchar(60),–联系电话
City nvarchar(50) default ‘北京’,–居住城市
Description ntext –作者简介
)

--上述是创建表格时直接设置约束,也可在表格建立之后再设定约束--添加主键约束(将AuthorID作为主键)alter table Authors

add constraint pk_AuthorID primary key(AuthorID);

–添加默认约束(性别默认值为1)
alter table Authors
add constraint DF_Sex DEFAULT(1) for Sex;

--添加检查约束(电子邮箱必须包含@)alter table Authors

add constraint CK_Emial Check(Email like ‘%@%’);

--删除约束alter table Authors drop DF_Sex;/*插入数据*/--单数据插入--方式一INSERT INTO Authors (AuthorName,Sex,Age,Email,TelPhone,City) VALUES ('吴玉鹏',1,47,'wyp@sohu.com','01090876529','北京') --方式二 insert into Authors values ('admin',1,'1997-02-12',20,'1484155104@qq.com','18273255013','株洲',null) --多行插入 INSERT INTO Authors (AuthorName,Sex,Age,Email,TelPhone,City)VALUES  ('吴玉鹏1',1,47,'wyp@sohu.com','01090876529','北京'), ('吴玉鹏2',1,47,'wyp@sohu.com','01090876529','北京'), ('吴玉鹏3',1,47,'wyp@sohu.com','01090876529','北京'), ('吴玉鹏4',1,47,'wyp@sohu.com','01090876529','北京'); INSERT INTO Authors (AuthorName, Sex, Age, Email, TelPhone)SELECT '张笑林',1,30,'zxl@163.com','02067839876' UNIONSELECT '李辉',0,52,'lh@126.com','02167345987' UNIONSELECT '洪海波',1,40,'hhb@163.com','031189654329'/*修改数据*/--将作者表中所有作者的居住城市都更改成“北京” update Authors set City='长沙';--将作者表中AuthorID为102的作者年龄更改成36岁 update Authors set Age=36 where AuthorID=102;--更新语句中还可以使用表达式 

update Authors set Age=Age-2 where AuthorID=102 or AuthorID=104;

/删除语句/

delete from Authors where AuthorID=102;

0 0