smiles

导航

SQLServer

E-R图:实体关系图
--矩形:实体
--椭圆:属性
--菱形:关系

三大范式:
--1NF:有主键,列不可再分
--2NF:满足1NF,没有部分依赖(一个表只描述一件事情)
--3NF:满足2NF,没有传递依赖(非主键字段不能被非主键字段推出)

数据库的三类文件
--主数据文件:mdf(1个)
--次要数据文件:ndf(0-N个)
--日志文件:ldf(1-N个)

创建数据库
if exists(select * from sysdatabases where name='数据库名')
 drop database 数据库名
go

create database 数据库名
on 
(
 name=逻辑名,
 filename=物理名称,
 size=初始化大小,
 maxsize=最大大小,
 filegrowth=文件增长大小/文件增长率
),
(
  ...  -- 次要数据文件
)
log on
(
  ...  -- 日志文件
)

创建表
if exists(select * from sysobjects where name='表名')
 drop table 表名
go

create table 表名
(
 字段1 类型 约束,
 字段2 类型 约束,
 ...
)
go

添加约束
alter table 表名 add
  constraint pk_列名 primary key(主键列),  -- 主键
  constraint uq_列名 unique(列),    -- 唯一
  constraint df_列名 default(默认值) for 列,  -- 默认
  constraint ck_列名 check(检查条件),   -- 检查
  constraint fk_列名 foreign key(外键) references 主表(主键) -- 外键
go

变量
--局部变量
  --定义:declare @变量名 类型
  --赋值:
    --set @变量名 = 值,直接赋值
    --select @变量名 = 值,从查询结果中赋值
--全局变量
  --@@error:获得最后一句SQL的错误号
    >0:错误
    =0:正确
  --@@rowcount:获得最后一句SQL受影响的行数
  --@@identity:获得最新的自动编号

显示
--Print:文本显示
--Select:网格显示

别名
--Select 别名=值
--Select 值 as 别名

类型转换
--Cast(值 as 类型)
--Convert(类型,值)

查询公式:
select 字段
from 表
where 条件
group by 分组
having 分组后的条件
order by 排序

select 字段 into 新表
from 旧表

insert into 旧表1
select 字段 from 旧表2

事务的公式:
begin transation -- 开始事务
declare @errSum int
set @errSum = 0
操作1
set @errSum = @errSum + @@error
操作2
set @errSum = @errSum + @@error
...
if (@errSum <> 0)
 rollback transaction -- 回滚事务
else
 commit transaction -- 提交事务
go

索引的分类:
--聚集索引:数据的顺序和键的顺序一致(1个)
--非聚集索引:和数据的顺序无关(249个)

创建索引
if exists(select * from sysindexes where name='索引名')
 drop index 表名.索引名
go

create nonclustered|clustered index 索引名
on 表(字段)
with fillfactor = 填充因子的数字
go

select * from 表(index=索引名)

创建视图
if exists(select * from sysobjects where name='视图名')
 drop view 视图名
go

create view 视图名
as
  查询语句
go


创建存储过程
if exists(select * from sysobjects where name='存储过程名')
 drop procedure 存储过程名
go

create procedure 存储过程名
  @参数 类型 [=默认值] [output],
  @参数 类型 [=默认值] [output]
  ..
as
  SQL语句
go

调用:
--默认:exec 存储过程名
--带返回参数
  declare @变量 类型
  exec 存储过程名 @变量 output
--带返回值
  declare @变量 类型
  exec @变量=存储过程名 参数1,参数2

posted on 2009-01-11 14:22  心欣  阅读(220)  评论(0编辑  收藏  举报