程序员,说到sqlserver中的复制表数据,我们一定会想到这两个语句:select into from和insert into select from
一.select into from语句(创建新表)
select into from语句用于创建一个新表,并将现有表中的数据插入到新表中,新表的结构将基于现有表的结构。
1. 用select into语句自动生成临时表,不需要我们手动创建
select * into #temp from staff
select * from #temp
如果当前会话中,已存在相同名字的临时表,你再去执行:
select * into #temp from staff
则会出现报错提示:数据库中已存在名为 '#temp' 的对象
所以在使用select into前,我们可以先做一下判断:
if object_id('tempdb..#temp') is not null
drop table #temp
select * into #temp from staff
select * from #temp
2. 利用select into生成一个空表
如果我们只需要一个空的表结构,可以在sql语句后面加一个条件,where 1=6:
select * into staffclone from staff where 1=6
select * from staffclone
3.复制表数据
如果程序员们想要复制表结构以及表里的数据:
select * into staffclone from staff
select * from staffclone
二.inser into select from语句(表已存在),用于将数据从一个表复制到另一个已经存在的表中。
1. 使用insert into语句,需要先手动创建表:test_staff
create table [dbo].[test_staff](
[sid] [varchar](10) not null,
[sname] [nvarchar](10) null,
[sage] [datetime] null,
[ssex] [nvarchar](10) null,
[slevel] [varchar](50) null,
[ssalary] [decimal](18, 2) null
) on [primary]
go
insert into test_staff select * from staff
2.当然,我们还可以带条件的进行批量插入:
insert into test_staff select * from staff where ssalary>20000
3.我们在批量插入时,还可以对数据进行计算或转换
insert into test_staff select sid,sname+' 程序员',sage,ssex,slevel,ssalary*1.2 from staff where ssalary<230000