sql 數據庫插入select into from 和 insert in

兩個數據庫在同一臺服務器上

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 :當目標數據庫中要插入數據的表已經存

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章