sql 数据库插入select into from 和 insert into select from

两个数据库在同一台服务器上

create TABLE Table1
    (
        a varchar(10) PRIMARY KEY,
        b varchar(10),
        c varchar(10)
    ) 

    create TABLE Table2
    (
        a varchar(10) PRIMARY KEY,
        c varchar(10),
        d int,
    )
    GO
    --2.创建测试数据
    Insert into Table1 values('a','aa','90')
    Insert into Table1 values('b','bb','100')
    Insert into Table1 values('c','cc','80')
    Insert into Table1 values('d','dd',null)
    GO
    select * from Table1

    --3.INSERT INTO SELECT语句复制表数据
    Insert into Country.dbo.Table2(a, c, d) select a,c,1 from Galaxy2012.dbo.Table1
    GO

    --4.显示更新后的结果
    select * from Table2
    GO
    --5.删除测试表
    drop TABLE Table1
    drop TABLE Table2



两个数据库不在同一个服务器上

exec sp_configure 'show advanced options',1
reconfigure
exec sp_configure 'Ad Hoc Distributed Queries',1
reconfigure
--当前数据库中不存在AddressMain时用
select * into AddressMain from openrowset('SQLOLEDB' 
, '服务器名称'; '用户名'; '密码' 
,数据库名.dbo.AddressMain)

--当前数据库中存在AddressMain时用
delete from AddressMain
insert into AddressMain select * from openrowset('SQLOLEDB' 
, '服务器名称'; '用户名'; '密码'  
,数据库名.dbo.AddressMain)SELECT *FROM OPENDATASOURCE( 'SQLOLEDB', 'Data Source=服务器名;User ID=用户名;Password=密码' ).数据库名.dbo.AddressMainexec sp_configure 'Ad Hoc Distributed Queries',0reconfigureexec sp_configure 'show advanced options',0reconfigure


select into from:当目标数据库中还不存在要插入数据的表
insert into select from :当目标数据库中要插入数据的表已经存在


猜你喜欢

转载自blog.csdn.net/xiongxyt2/article/details/8475589