日期:2014-05-17 浏览次数:20662 次
----------------------------
-- Author :TravyLee(物是人非事事休,欲语泪先流!)
-- Date :2012-11-28 09:36:30
-- Version:
-- Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86)
-- Feb 10 2012 19:13:17
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
go
create table [test]([城市] varchar(6),[城市码] int,[上一级代码] int)
insert [test]
select '浙江省',1100,-1 union all
select '杭州市',1110,1100 union all
select '西湖区',1111,1110 union all
select '上城区',1112,1110 union all
select '金华市',1120,1100 union all
select '下城区',1113,1120
select * from [test]
go
declare @上一级代码 int
set @上一级代码=1110
select
*
from
test a
where
exists(select 1 from test b where a.上一级代码=b.城市码)
and case when exists (select 1 from test where 上一级代码=@上一级代码 )
then 上一级代码 else [城市码] end=@上一级代码
/*
城市 城市码 上一级代码
------ ----------- -----------
西湖区 1111 1110
上城区 1112 1110
(2 行受影响)
*/
USE tempdb
GO
-- 建立演示环境
CREATE TABLE Dept(
id int PRIMARY KEY,