有两个Table,我想取得全部资料。
<<Table A>>
Date Name
3/20 AA
3/19 BB
3/18 CC
<<Table B>>
Date Name
3/21 DD
这种情况,两个Table没有相同的日期,所以我用了UNION ALL取得全部资料
但如果Table A有一笔3/21的资料,形成:
<<Table A>>
Date Name
3/21 XX
3/20 AA
3/19 BB
3/18 CC
<<Table B>>
Date Name
3/21 DD
这时我希望结果是(若相同日期,则以Table A的Name为主)
Date Name
3/21 XX
3/20 AA
3/19 BB
3/18 CC
要怎样的SELECT指令才能同时适用这两种情形(有相同日期&没有相同日期)呢?
------解决方案--------------------
----------------------------------------------------------------
-- 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 行受影响)
*/