管志鹏的计算机主页

C# ASP.NET Java J2EE SSH SQL Server Oracle
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

数据库练习

Posted on 2008-08-29 20:49  管志鹏  阅读(252)  评论(0编辑  收藏  举报

 

2008-3-20

  1这是今天做的数据库,感觉都生孰了.技术这东西啊,一定得常用啊.
  2
  3 
  4
  5use master 
  6
  7go 
  8/*判断stuDB是否存在,如果存在,则删除,然后再创建数据库*/
  9if exists(select * from sysdatabases where name = 'stuDB')
 10
 11drop database stuDB
 12
 13create database stuDB
 14
 15on primary --主文件组,可省略
 16(
 17name = 'stuDB_data',--主数据库文件的逻辑名 
 18filename = 'F:\Sql\stuDB\stuDB_data.mdf',--主数据库文件的物理名
 19size = 5mb,
 20maxsize = 100mb,
 21filegrowth = 15%
 22)
 23log on(
 24
 25name = 'stuDB_log',
 26filename = 'F:\Sql\stuDB\stuDB_log.ldf',
 27size = 2mb,
 28filegrowth = 1mb
 29)
 30go
 31
 32
 33use stuDB
 34
 35--创建表stuInfo
 36create table stuInfo
 37(
 38stuName varchar(20not null--姓名
 39stuNo char(6not null,--学号
 40stuAge int not null,--年龄
 41stuID numeric(18,0),--身份证号
 42stuSeat smallint identity(1,1),--座位号,自动标识列
 43stuAddress text --住址
 44
 45)
 46go
 47--创建表stuMarks
 48create table stuMarks
 49(
 50ExamNo char(7not null,--考试号
 51stuNo char(6not null,--学号
 52labExam int not null--机试成绩
 53)
 54go
 55
 56--添加主键约束
 57alter table stuInfo
 58add constraint PK_stuNo primary key(stuNo)
 59
 60--添加唯一约束
 61alter table stuInfo
 62add constraint UQ_stuID unique(stuID)
 63
 64--添加默认约束(地址为"地址不祥")
 65alter table stuInfo
 66add constraint DF_stuAddress default('地址不祥')for stuAddress
 67
 68--添加Check约束(年龄在15到40之间)
 69alter table stuInfo
 70add constraint CK_stuAge check(stuAge between 15 and 40)
 71
 72--添加外键约束
 73alter table stuMarks
 74add constraint FK_stuNo
 75foreign key (stuNo) references stuInfo(stuNo)
 76
 77--添加ckeck约束
 78alter table stuMarks
 79add constraint CK_labExam check(labExam between 0 and 100)
 80
 81go
 82
 83--创建登录帐户
 84
 85--创建Windows登录帐户(如果创建的域用户,则用'域名\用户名',如果是Window本地用户,则用'计算机名\用户名')
 86 exec sp_grantlogin 'HP-Gzp\administrator'
 87
 88--创建SQL登录帐户
 89 exec sp_addlogin 'gzp','1234'
 90
 91--创建数据库用户
 92
 93exec sp_grantdbaccess 'HP-Gzp\administrator','gzp'
 94    /*'HP-Gzp\administrator':为登录帐户,'gzp'为添加的数据库用户*/
 95
 96exec sp_grantdbaccess 
 97
 98--向数据库用户授权
 99
100--grant 权限 [on 表名] to 数据库用户
101
102grant select,insert  on stuInfo to gzp
103
104