1. 資料庫文件包括:
主資料檔:*.mdf
次要資料檔:*.ndf
日誌檔:*.ldf ( l 是L 的小寫)
2.使用T-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:stuDB_data.mdf',
size=3mb,
maxsize=10mb,
filegrowth=1mb
)
log on
(
name='stuDB_log',
filename='D:stuDB_data.ldf',
size=1mb,
filegrowth=1mb
)
3.使用T-SQL 建立資料庫表
程式碼
-----------建立資料庫表格------------
use stuDB
go
if exists (select * from sysobjects where name='stuInfo')
drop table stuInfo
create table stuInfo
(
stuName varchar(20) not null,
stuNo char(6) not null,
stuAge int not null,
stuID numeric(18,0),--身分證
stuSeat smallint identity(1,1),
stuAddress text
)
go
if exists (select * from sysobjects where name='stuMarks')
drop table stuMarks
create table stuMarks
(
ExmaNo char(7) not null, --考號
stuNo char(6) not null,--學號
writtenExam int not null,--筆試成績
LabExam int not null--機試成績
)
go
4. 新增約束
程式碼
--------------新增約束-----------------
alter table stuinfo --修改stuinfo表
add constraint PK_stuNo primary key (stuNo)--新增主鍵PK_stuNo是自訂的主鍵名稱也可以省略
alter table stuinfo
add constraint UQ_stuID unique (stuID) --新增唯一約束
alter table stuinfo
add constraint DF_stuAddress default ('位址不詳') for stuAddress--新增預設 不填預設'位址不詳'
alter table stuinfo
add constraint CK_stuAge check(stuAge between 18 and 60) --新增檢查約束18-60歲
alter table stuMarks
add constraint FK_stuNo foreign key(stuNo) references stuInfo(stuNo)
go
5.刪除約束
-------------刪除約束--------------
alter table stuinfo
drop constraint 約束名稱--如:FK_stuNo CK_stuAge DF_stuAddress UQ_stuID PK_stuNo