一次插入多条记录,mysql与SQLServer的不同操作

来源:互联网 发布:js strings.format 编辑:程序博客网 时间:2024/05/18 01:04

今天看一个面试例子的时候。输入插入一组数据

当在SQLServer中的查询分析器内,把那段mysql创建表和插入表的语句复制进去的时候,运行错误了,在网上查找学习后才发现,是两个数据库语言的不同造成的。

mysql语句:

drop table if exists tea_stu;

drop table if exists teacher;

drop table if exists student;

      create table teacher(teaID int primary key,name varchar(50),age int);

      create table student(stuID int primary key,name varchar(50),age int);

      create table tea_stu(teaID int references teacher(teaID),stuID int references student(stuID));

insert into teacher values(1,'zxx',45), (2,'lhm',25) , (3,'wzg',26) , (4,'tg',27);

insert into student values(1,'wy',11), (2,'dh',25) , (3,'ysq',26) , (4,'mxc',27);

insert into tea_stu values(1,1), (1,2), (1,3);

insert into tea_stu values(2,2), (2,3), (2,4);

insert into tea_stu values(3,3), (3,4), (3,1);

insert into tea_stu values(4,4), (4,1), (4,2) , (4,3);

 

这段语句在mysql中运行的话是正确的,

而在SQLServer中,drop table  if是无效的,

而且,insert 语句不能这样写insert into teacher values(1,'zxx',45), (2,'lhm',25) , (3,'wzg',26) , (4,'tg',27);

而是得老老实实写成:

insert into teacher(teaID ,name,age)values (1,'zxx',45);

insert into teacher(teaID ,name,age)values(2,'lhm',25);

insert into teacher(teaID ,name,age)values (3,'wzg',26);

insert into teacher(teaID ,name,age)values (4,'tg',27);

 

或者,采取网上查的那种更省力的一种方法:

insert into teacher(teaID,name,age)
select 1,'zxx',45
union all
select 2,'lhm',25
union all
select 3,'wzg',26
union all
select 4,'tg',27

 

基本格式是:

create table #(a int,b int)

insert into #(a,b)
select 1,2
union all
select 2,3
union all
select 3,4

 

但是,发现也有人只用union,而不用union all,我想,前者应该是自动删除重复数据,后者插入时是允许插入重复数据吧(个人理解)

通过这个,可以提醒我们,注意mysql和SQLServer的差别,避免混淆操作的杯具发生。

 

 

 

 

 

 

 

 

原创粉丝点击