表1 字段1 字段2 字段3
值: A B 3
A C 4
表2 字段1 字段2 字段3
值: A B 5
A D 4
表1 和 表2 进行比较 如果字段1和字段2 不一致将表2中的新记录插到表1 中 ,上述两个表运算完应该是:
表1 字段1 字段2 字段3
值: A B 3
A C 4
A D 4
------解决方案--------------------
表中的列A,B,C分别对应你的字段1、2、3
----------------------------------------------------------------
-- Author :DBA_HuangZJ(发粪涂墙)
-- Date :2014-04-30 08:26:55
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64)
-- Apr 2 2010 15:48:46
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([a] nvarchar(2),[b] nvarchar(2),[c] int)
insert [A]
select 'A','B',3 union all
select 'A','C',4
--> 测试数据[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([a] nvarchar(2),[b] nvarchar(2),[c] int)
insert [B]
select 'A','B',5 union all
select 'A','D',4
--------------生成数据--------------------------
INSERT INTO A(a,b,c)
select * from [B]
WHERE NOT EXISTS (SELECT 1 FROM [A] WHERE (a.a=b.a and a.b=b.b))
select * from [A]
----------------结果----------------------------
/*
a b c
---- ---- -----------
A B 3
A C 4
A D 4
*/
------解决方案--------------------
IF OBJECT_ID(N'[表1]') IS NOT NULL
DROP TABLE [表1]
Go
CREATE TABLE [表1]
(
[a] NVARCHAR(2) ,
[b] NVARCHAR(2) ,
[c] INT
)
INSERT [表1]
SELECT 'A' ,
'B' ,
3
UNION ALL
SELECT 'A' ,
'C' ,
4
IF OBJECT_ID(N'[表2]') IS NOT NULL
DROP TABLE [表2]
go
CREATE TABLE [表2]
(
[a] NVARCHAR(2) ,
[b] NVARCHAR(2) ,
[c] INT
)
INSERT [表2]
SELECT 'A' ,
'B' ,
5
UNION ALL
SELECT 'A' ,
'D' ,
4