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 視圖名