日期:2014-05-18 浏览次数:20708 次
Create PROCEDURE [dbo].[backup_001]
AS
BEGIN
SET NOCOUNT ON;
SET IDENTITY_Insert t_001 ON
merge t_001 d
using
(SELECT * FROM OPENQUERY (xx2008 ,'select * from c_001.dbo.t_001' ) ) s
on (d.id=s.id and d.updatetime <>s.updatetime)
WHEN NOT MATCHED BY SOURCE THEN delete
when matched then
update set
d.f1=s.f1,
d.f2=s.f2,
d.f3=s.f3,
......
d.updatetime=s.updatetime
when not matched then
insert (d.f1,d.f2,d.f3,......d.updatetime)
values (s.f1,s.f2,s.f3,......s.updatetime);
SET IDENTITY_Insert t_001 OFF
END
--merge主要用于两表之间的关联操作 有两张结构一致的表:test1,test2 create table test1 (id int,name varchar(20)) go create table test2 (id int,name varchar(20)) go insert into test1(id,name) values(1,'boyi55'),(2,'51cto'),(3,'bbs'),(4,'fengjicai'),(5,'alis') insert into test2(id,name) values(1,'boyi'),(2,'51cto') merge test2 t --要更新的目标表 using test1 s --源表 on t.id=s.id --更新条件(即主键) when matched --如果主键匹配,更新 then update set t.name=s.name when not matched then insert values(id,name);--目标主未知主键,插入。此语句必须以分号结束 select a.id,a.name as name_1,b.name as name_2 from test1 as a,test2 as b where a.id=b.id /* id name_1 name_2 ----------- -------------------- -------------------- 1 boyi55 boyi55 2 51cto 51cto 3 bbs bbs 4 fengjicai fengjicai 5 alis alis*/
------解决方案--------------------
路过。
------解决方案--------------------
IF OBJECT_ID (N'dbo.Departments', N'U') IS NOT NULL DROP TABLE dbo.Departments; GO CREATE TABLE dbo.Departments (DeptID tinyint NOT NULL PRIMARY KEY, DeptName nvarchar(30), Manager nvarchar(50)); GO INSERT INTO dbo.Departments VALUES (1, 'Human Resources', 'Margheim'),(2, 'Sales', 'Byham'), (3, 'Finance', 'Gill'),(4, 'Purchasing', 'Barber'), (5, 'Manufacturing', 'Brewer'); GO SELECT * FROM dbo.Departments GO IF OBJECT_ID (N'dbo.Departments_delta', N'U') IS NOT NULL DROP TABLE dbo.Departments_delta; GO CREATE TABLE dbo.Departments_delta (DeptID tinyint NOT NULL PRIMARY KEY, DeptName nvarchar(30), Manager nvarchar(50)); GO INSERT INTO dbo.Departments_delta VALUES (1, 'Human Resources', 'Margheim'), (2, 'Sales', 'Erickson'), (3 , 'Accounting', 'Varkey'),(4, 'Purchasing', 'Barber'), (6, 'Production', 'Jones'), (7, 'Customer Relations', 'Smith'); GO SELECT * FROM dbo.Departments_delta G