日期:2014-05-16 浏览次数:20523 次
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-25 17:31:27
-- Verstion:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[TableA]
if object_id('[TableA]') is not null drop table [TableA]
go
create table [TableA]([Date] varchar(4),[Name] varchar(2))
insert [TableA]
select '3/21','XX' union all
select '3/20','AA' union all
select '3/19','BB' union all
select '3/18','CC'
--> 测试数据:[TableB]
if object_id('[TableB]') is not null drop table [TableB]
go
create table [TableB]([Date] varchar(4),[Name] varchar(2))
insert [TableB]
select '3/21','DD'
--------------开始查询--------------------------
IF EXISTS(SELECT 1 FROM dbo.TableA AS a WHERE EXISTS(SELECT 1 FROM dbo.TableA WHERE Date=a.Date))
SELECT * FROM dbo.TableA
UNION ALL
SELECT * FROM dbo.TableB AS a WHERE NOT EXISTS(SELECT 1 FROM dbo.TableA WHERE Date=a.Date)
ELSE
SELECT * FROM dbo.TableA
UNION ALL
SELECT * FROM dbo.TableB
----------------结果----------------------------
/* Date Name
---- ----
3/21 XX
3/20 AA
3/19 BB
3/18 CC
(4 行受影响)
*/