smiles

导航

sql普通代码

USE MASTER
GO

IF EXISTS(SELECT * FROM SYSDATABASES WHERE NAME='stuDB')
drop database stuDB

create database stuDB
on primary
(
 name='stuDB_data',
 filename='D:\DB\stuDB_data.mdf',
 size=5mb,
 maxsize=100mb,
 filegrowth=15%
)
log on
(
 name='stuDB_log',
 filename='D:\DB\stuDB_log.ldf',
 size=2mb,
 filegrowth=1mb
)
go


use stuDB
go
--创建学员信息表
if exists(select * from sysobjects where name='stuInfo')
drop table stuInfo
go
create table stuInfo
(
 stuName varchar(20) not null, --学员姓名,非空(必填)
 stuNo char(6) not null, --学号,非空(必填)
 stuAge int not null, --年龄,int类型不用指定大小,默认为4个字节
 stuID numeric(18,0),--身份证号,numeric(18,0)代表18位数字,小数位数为0
 stuSeat smallint identity(1,1), --座位号,自动编号(标识列),从1开始递增
 stuAddress text --住址,允许为空,即可选输入
)
--创建学员成绩表
if exists(select * from sysobjects where name='stuMarks')
drop table stuMarks
go
create table stuMarks
(
 ExamNo char(7) not null, --考号
 stuNo char(6) not null, --学号
 writtenExam int not null, --笔试成绩
 labExam int not null --机试成绩
)

/**************************  使用SQL语句创建和删除约束 ******************************/
--添加主键约束
alter table stuInfo add constraint PK_stuNo primary key(stuNo)
--添加唯一约束(身份证号唯一)
alter table stuInfo add constraint UQ_stuID unique(stuID)
--添加默认约束(如果地址不填,默认为"地址不详")
alter table stuInfo add constraint DF_stuAddress default('地址不详') for stuAddress
--添加检查约束,要求年龄只能在15-40岁之间
alter table stuInfo add constraint CK_stuAge check(stuAge between 15 and 40)
--添加外键约束(主表stuInfo和从表stuMarks建立关系,关联字段为stuMarks)
alter table stuMarks add constraint FK_stuNo foreign key(stuNo) references stuInfo(stuNo)
go

/*************************************  删除约束 **********************************************/
--删除约束的语法是: alter table 表名 drop constraint 约束名
alter table stuInfo drop constraint DF_stuAddress

/************************************* 创建登录帐户 ************************************/
--  windows 登录帐户语法 :   exec sp_grantlogin 'windows 域名\域帐户'
--SQL Server 登录帐户语法:   exec sp_addlogin '账号','密码'

/*--添加 windows 登录账号--*/
exec sp_grantlogin 'jbtraining\s26301'
--windows用户为 jbtraining\s26301 ,jbtraining 表示域

/*--添加 SQL 登录账号--*/
exec sp_addlogin 'zhangsan','1234'  --帐户名为 zhangsan ,密码为 1234
go

/*************************************  创建数据库用户 **********************************************/
--语法:exec sp_grantdbaccess '登录帐户','数据库用户'

/*-- 在stuDB数据库中添加两个用户 --*/
use stuDB
go
exec sp_grantdbaccess 'jbtraining\s26301','s26301DBUser'
exec sp_grantdbaccess 'zhangsan','zhangsanDBUser' --zhangsanDBUser为数据库用户

/*************************************  给数据库用户授权 **********************************************/
--语法为:grant 权限 [on 表名] to 数据库用户

grant select,insert,update on stuInfo to zhangsanDBUser

grant create table to s26301DBUser


 

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