use master
go
--为创建数据库BankDB布置环境
exec sp_configure 'show advanced options' , 1
go
RECONFIGURE
go
exec sp_configure 'xp_cmdshell' , 1
go
RECONFIGURE
go
--创建文件夹D:\MyWorkspaces\DB\BankDB
exec xp_cmdshell 'mkdir D:\MyWorkspaces\DB\BankDB'
go
--如果同名的数据库已经存在,删除之
if exists (select * from sysdatabases where name = 'BankDB')
drop database BankDB
go
exec sp_configure 'xp_cmdshell' , 0
go
RECONFIGURE
go
exec sp_configure 'show advanced options' , 0
go
RECONFIGURE
go
--创建数据库BankDB
create database BankDB
on primary
(
name = 'BankDB_data',
filename = 'D:\MyWorkspaces\DB\BankDB\BankDB_data.mdf',
size = 10MB,
maxsize = 100MB,
filegrowth = 15%
)
log on
(
name = 'BankDB_log',
filename = 'D:\MyWorkspaces\DB\BankDB\BankDB_log.ldf',
size = 10MB,
maxsize = 100MB,
filegrowth = 15%
)
go
CREATE TABLE- 创建新表
语法:
create table 表名
(
列名 数据类型 [constraint 约束名] [primary key][foreign key references 表名(列名)][default (值)][check(check约束内容)][unique] [not null][,]
...
约束
...
--最后一个逗号可写,建议不写,以便与oracle兼容
--约束名命名规范:{PK|FK}_列名_意义名
--默认情况下,主键的取值范围不包括空值,但唯一键则不然,且当唯一键取空值时,在sql server中不允许重复,但oracle则可
)
实例:
create table Account
(
acc_id int primary key identity(1,1),
accountNo varchar(16) unique check( len(accountNo) = 16 and accountNo not like '%[^0-9]%' and accountNo like '10103576%') ,
ID varchar(18) references Depositor(ID) not null ,
password varchar(6) check(len(password) = 6 and password not like '%[^0-9]%') default '888888' not null,
currencyType varchar(20) default 'RMB' not null ,
depositTypeID int references DepositType(depositTypeID) not null ,
openDate datetime default getdate() not null ,
openMoney money check(openMoney >= 1) not null ,
currentMoney money check(currentMoney >= 1) not null ,
isLoss bit default 0 not null
)
go
ALTER TABLE- 变更(改变)数据库表
alter table 表名 add 列名 列数据类型--添加列,注意这里没有column关键字
alter table 表名 drop column 列名 --删除列
alter table 表名 alter column 列名 列数据类型 --修改列
alter table 表名 add constraint 约束名 约束内容
alter table 表名 drop 约束名
DROP TABLE- 删除表
drop table 表名
CREATE VIEW- 创建视图
create view 视图名 as 查询语句
DROP VIEW--删除视图
drop view 视图名