日期:2014-05-17  浏览次数:20639 次

如何把sql脚本搞成可以动态生成数据库、表、字段的sql脚本
--创建数据库
create database northwind
on
(name="northwind",
 filename="F:\sql2008data\northwind.mdf",
 size=3,
 maxsize=10,
 filegrowth=2%
)
go
create database practice
on
(name="practice",
 filename="F:\sql2008data\practice.mdf",
 size=3,
 maxsize=10,
 filegrowth=2%
)
go
--创建数据表
use northwind
create table teachers
([tid] int identity(1,1) not null,
 [name] varchar(10),
 [age] int,
 [address] varchar(50),
 [sex] bit,
 [tel] int
)
go
create table students
([sid] int identity(1,1) not null,
 [name] varchar(10),
 [age] int, 
 [address] varchar(50),
 [sex] bit,
 [tel] int,
 [tid] int
)
go
use practice
create table newstype
(tid int identity(1,1) not null,
 tname varchar(10) not null,
 tdescription varchar(100)
)
go
create table news
([nid] int identity(1,1) not null,
 [name] varchar(50),
 [writer] varchar(10),
 [time] datetime,
 [source] varchar(10),
 [content] varchar(8000),
 [tid] int
)
go
--创建索引
use northwind
create index i_students_name on students(name)
go
use practice
create index i_news_name on news(name)
go
--添加约束northwind
use northwind
alter table teachers
add constraint PK_tid primary key(tid)
alter table teachers
add constraint UK_name unique(name)
alter table teachers
add constraint CK_age check(age between 20 and 120)
alter table teachers
add constraint DF_address default('中国大陆') for address
alter table students
add constraint PK_sid primary key(sid)
alter table students
add constraint UK_names unique(name)
alter table students
add constraint CK_ages check(age between 0 and 120)
alter table students
add constraint DF_addresses default('中国大陆') for address
alter table students
add constraint FK_tid foreign key(tid) references teachers(tid)
--添加约束practice
use practice
alter table newstype
add constraint PK_tid primary key(tid)
alter table news
add constraint PK_nid primary key(nid)
alter table news
add constraint UK_name unique(name)
alter table news
add constraint DF_time default(getdate())for time
alter table news
add constraint FK_tid foreign key(tid) references newstype(tid)