您的位置:首页 > 数据库

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

2015-12-02 16:56 417 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yingziok888/article/details/50150643

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';

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐