62,046
社区成员
发帖
与我相关
我的任务
分享
create table #temp(
nodeid int,
name varchar(100),
parentid int)
insert #temp values (1 ,'广东', 0)
insert #temp values (2 ,'广西',0)
insert #temp values (3 ,'湖南',0)
insert #temp values (4 ,'广州',1)
insert #temp values (5 ,'中山',1)
insert #temp values (6 ,'番禺',1)
insert #temp values (7 ,'南宁',2)
insert #temp values (8 ,'桂林',2)
insert #temp values (9 ,'柳州',2)
insert #temp values (10,'长沙',3)
select nodeid,name,(select name from #temp b where a.parentid=b.nodeid) as parentid from #temp a
----------------------------------------------------------------
-- Author :SQL77(只为思齐老)
-- Date :2010-03-26 08:56:20
-- Version:
-- Microsoft SQL Server 2000 - 8.00.194 (Intel X86)
-- Aug 6 2000 00:57:48
-- Copyright (c) 1988-2000 Microsoft Corporation
-- Desktop Engine on Windows NT 5.1 (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:#TB
if object_id('tempdb.dbo.#TB') is not null drop table #TB
go
create table #TB([nodeid] int,[name] varchar(4),[parentid] int)
insert #TB
select 1,'广东',0 union all
select 2,'广西',0 union all
select 3,'湖南',0 union all
select 4,'广州',1 union all
select 5,'中山',1 union all
select 6,'番禺',1 union all
select 7,'南宁',2 union all
select 8,'桂林',2 union all
select 9,'柳州',2 union all
select 10,'长沙',3
--------------开始查询--------------------------
select NODEID,NAME,(SELECT NAME FROM #TB WHERE NODEID=T.PARENTID)NAME from #TB T
----------------结果----------------------------
/*
(所影响的行数为 10 行)
NODEID NAME NAME
----------- ---- ----
1 广东 NULL
2 广西 NULL
3 湖南 NULL
4 广州 广东
5 中山 广东
6 番禺 广东
7 南宁 广西
8 桂林 广西
9 柳州 广西
10 长沙 湖南
(所影响的行数为 10 行)
*/