sql 建立数据库 建立表 建立约束

1.数据库文件构成: 
      主要数据文件:*.mdf
      次要数据文件:*.ndf
          日志文件:*.ldf
2.创建一个数据文件和一个日志文件
create database a
on primary(
name='Test_data',
filename='D:\Test_data.mdf',
size=5mb,
maxsize=100mb,
filegrowth=15%
)
log on(
name='Test_log',
filename='D:\Test_log.ldf',
size=2mb,
filegrowth=1mb
)
go
3.删除数据库
drop database a
4.检测是否存在数据库a
use master
go
if exists(select * from sysdatabases where name='a')
drop database a
5.创建表
use a
go 
create table s(
s_name varchar(20) not null,--学员姓名 非空
s_no   char(6)     not null,--学号 非空
s_age  int         not null,--年龄 int类型(默认为4个字节) 非空
s_id   numeric(18,0),-- 身份证号,numeric(18,0)代表18位数字,小数位数为0
s_seat smallint identity(1,2),--座位号,自动编号(标识列),从1开始递增每次增2
s_address text            --住址 允许为空

)
go
6.常用约束类型
主键约束(primary key constraint):要求主键列数据唯一,并且不允许为空
唯一约束(unique constraint):要求该列唯一,允许为空,但只能出现一个空值
检查约束(check constraint):某列取值范围限制、格式限制等
默认约束(default constraint):某列的默认值
外键约束(foreign key constraint):用于在两表间建立关系
7.添加约束
一般创建表跟约束是分开编写的
alter table s
add constraint PK_SNo primary key(s_no) --学号为主键的约束
alter table s
add constraint UQ_SId unique (s_id)  --身份证号唯一
alter table s
add constraint Df_SAdrress default('地址不详') for s_address
alter table s
add constraint C_SAge check(s_age between 15 and 40)
alter table s
add constraint FK_SNo
foreign key(s_no)references stuInfo(stuNo)
8.删除约束
alter table s
drop constraint PK_SNo
9.给数据库中添加多条记录
insert into s (s_name,s_sex)
select 'lin','sd'
union select 'sdf','ds'
10.创建登陆账户,需要调用内置的系统存储过程 sp_grantlogin
exec sp_grantlogin 'jbtraining\s26301'  --添加windows登陆账户     
exec sp_addlogin 'zhangsan', '123' --创建SQL登陆账户
exec sp_grantdbaccess 'zhangsan','sa' --创建数据库用户(给登陆账户授权)
grant insert,update,delete on s to sa  --给数据库用户授权


--删除权限 

revoke insert,delete on table1 from public 

--删除数据库中的用户 

exec sp_revokedbaccess '用户名' 

--删除用户 

exec sp_droplogin '用户名'   

--通过sp_addlogin创建登录名
execute sp_addlogin 'zhangsan','112233' 

11.banzhuren授权
exec sp_addlogin 'banzhuren', '11111' --创建sql账户 banzhuren
exec sp_grantdbaccess 'banzhuren' --授予banzhuren 账户访问数据库stuDB的权利
grant insert ,update ,select on stuInfo_1 to banzhuren -

猜你喜欢

转载自java-bckf.iteye.com/blog/2033517