--以操作系統命令行解釋器的方式執行給定的命令字符串,
--並以文本行的方式返回任何輸出
--在使用xp_cmdshell之前,需要執行 sp_configure以啓用xp_cmdshell
exec sp_configure 'show advanced options',1
go
reconfigure
go
exec sp_configure 'xp_cmdshell',1
go
reconfigure
go
--刪除一個文件夾
exec xp_cmdshell 'rd d:\MySchool'
--創建一個文件夾
exec xp_cmdshell 'mkdir d:\MySchool'
--創建一個數據庫
use master
go
if exists (select * from sysdatabases where name='MySchool1')
drop database MySchool1
create database MySchool1
on primary
(
name='MySchool1_data',
filename='d:\MySchool1_data.mdf',
size=10MB,
maxsize=100MB,
filegrowth=15%
)
log on
(
name='MySchool1_log',
filename='d:\MySchool1_data.ldf',
size=2MB,
filegrowth=1MB
)
go
--創建一張表並且添加約束
use MySchool
go
if exists(select * from sysobjects where name='Student1')
drop table student1
go
create table Student1
(
StudentNo int primary key check (len(StudentNo)>=6),
StudentName nvarchar(50) default '無名氏' not null,
LoginPwd nvarchar(50) check(len(LoginPwd)>=6),
Sex char(2) check (Sex='男' or Sex='女'),
Phone nvarchar(50) null,
BornDate date not null check (BornDate>='1990-01-01'),
Address nvarchar(255) default '地址不詳',
gradeId int
)
--創建年級表,給Student表外鍵約束使用
use MySchool
go
if exists(select * from sysobjects where name='grade')
drop table grade
create table grade
(
gradeId int primary key,
gradeName nvarchar(50) not null
)
--給Student表中增加一個列
alter table Student1
add idCard nvarchar(50) null
--給Student表中的idCard添加約束
alter table Student1
add constraint DF_idCard default '00000000' for idCard
--外鍵約束
alter table Student1
add constraint PK_gradeId foreign key(gradeId) references grade(gradeId)
--【擴展】
--查詢Stduent1表中所有的約束名
use MySchool
exec sp_helpconstraint @objname=Student1
go
--數據庫的備份
--備份
use master
backup database MySchool1 to disk='d:\MySchool' with format
----還原
use master
restore database MySchool1 from disk='d:\MySchool' with replace
用T-SQL創建數據庫,數據表,添加約束,數據備份
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.