SQLServer中创建外键和将txt中的内容导入到数据表中

来源:互联网 发布:装机软件推广联盟 编辑:程序博客网 时间:2024/05/17 01:46

SQLServer2008下:

1. 创建包含外键的表:

下面列举了两种方式:

create database xiaonei;

--国家表
create table country(
id int not null primary key identity(1,1),
name varchar(32) not null
);
--省份表
CREATE TABLE province(
id int not null primary key identity(1,1),
name varchar(32) not null,
countryId int REFERENCES country(id)   --外键countryId
)

--大学表(大学的公共信息部分)
create table university(
id int not null primary key identity(1,1),
name varchar(64) not null,
countryId int,
proId int,
foreign key (countryId) references country(id),    --外键countryId
foreign key (proId) references province(id)        --外键proId

)

2. 将txt中的内容导入到数据库表中

 txt中的内容:

1 北京1
2 上海1
3 天津1
4 重庆1
5 黑龙江1

内容每一行的字段之间是用tab键分隔的,行与行之间是用回车换行符分隔的

将txt拷贝到e:\data\province.txt

在SQLServer中执行命令:

--从txt文件导入数据
bulk insert dbo.province.txt
from 'e:\data\province.txt'
with (
fieldterminator = '\t',   --以制表符横向分隔
rowterminator = '\n'    --以\n回车换行
)

MySQL中实现上面两个功能的命令是:

1. --省份表
CREATE TABLE province(
id int not null primary key auto_increment,
name varchar(32) not null,
countryId int,
FOREIGN KEY (countryId) REFERENCES country(id)

) TYPE=INNODB


--大学表(大学的公共信息部分)
create table university(
id int not null primary key auto_increment,
name varchar(64) not null,
countryId int,
proId int,
foreign key (countryId) references country(id),
foreign key (proId) references province(id)

)

2. load data local infile 'D:\\data.txt' into table 表名 fields terminated by '\t';

0 0
原创粉丝点击