日期:2014-05-18 浏览次数:20444 次
-------------------------------------- -- Author : htl258(Tony) -- Date : 2010-04-27 11:25:06 -- Version:Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) -- Jul 9 2008 14:43:34 -- Copyright (c) 1988-2008 Microsoft Corporation -- Developer Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 3) -- Blog : http://blog.csdn.net/htl258 -------------------------------------- --> 生成测试数据表:tb IF NOT OBJECT_ID('[tb]') IS NULL DROP TABLE [tb] GO CREATE TABLE [tb]([a] INT,[b] INT) INSERT [tb] SELECT 11,1 UNION ALL SELECT 11,2 UNION ALL SELECT 12,11 UNION ALL SELECT 12,3 UNION ALL SELECT 13,11 UNION ALL SELECT 13,12 GO --SELECT * FROM [tb] -->SQL查询如下: declare @i int set @i=13 ;with t as ( select * from tb where a=@i union all select a.* from tb a join t b on b.b=a.a ) select distinct @i a,b from t a where not exists(select 1 from t where a.b=a) order by b /* a b ----------- ----------- 13 1 13 2 13 3 (3 行受影响) */