sql server 的T-SQL 学习笔记(二)--- 解决union select插入多行数据过滤数据(union all)

来源:互联网 发布:视频展示台软件 编辑:程序博客网 时间:2024/05/16 11:29

学生表

use studentSysgo--创建学生表Studentif exists (select * from sys.objects where name ='Student') drop table studentSysgocreate table Student(  stuId int primary key identity,  stuName varchar(50) not null,  stuBornDay date not null,  stuSex nchar(1) not null,  stuAddress varchar(200),  classId int foreign key references Classes(classId))

主键自增情况下插入多行数据,插入相同数据时候,在这里插入三条,执行时候只显示 (2 行受影响) 这明显就不符合我预期想要的结果

 -- 插入多行数据(备份)    insert into Student (stuName,stuBornDay,stuAddress,stuSex,classId)       select '陈聪',GETDATE(),'湖北武汉','男',1      union select '张三',GETDATE(),'湖北武汉','女',2      union select '张三',GETDATE(),'湖北武汉','女',2

解决方法:
因为在插入相同数据时候 union会自动过滤相同数据

UNION 操作符用于合并两个或多个 SELECT 语句的结果集。默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL

那么上面的insert语句可以修改成这样

 insert into Student (stuName,stuBornDay,stuAddress,stuSex,classId)       select '陈聪',GETDATE(),'湖北武汉','男',1      union all select '张三',GETDATE(),'湖北武汉','女',2      union all select '张三',GETDATE(),'湖北武汉','女',2

关于unionunion all 的详细用法可以参见w3c上的详解,传送门 : SQL UNION 和 UNION ALL 操作符