如何用SQL语句,在一个表里面判断逐级编码以及逐级对应名称,从而实现末级编码对应逐级拼接名称?
发布网友
发布时间:2022-04-09 13:04
我来回答
共1个回答
热心网友
时间:2022-04-09 14:34
SQL带递归的语法 参考如下sqlserver 真他数据库也有类似
IF OBJECT_ID('tb') IS NOT NULL
DROP TABLE tb
create table tb(id varchar(3) , pid varchar(3) , name varchar(10))
insert into tb values('001' , null , '广东省')
insert into tb values('002' , '001' , '广州市')
insert into tb values('003' , '001' , '深圳市')
insert into tb values('004' , '002' , '天河区')
insert into tb values('005' , '003' , '罗湖区')
insert into tb values('006' , '003' , '福田区')
insert into tb values('007' , '003' , '宝安区')
insert into tb values('008' , '007' , '西乡镇')
insert into tb values('009' , '007' , '龙华镇')
insert into tb values('010' , '007' , '松岗镇')
GO
SELECT * FROM tb AS t
DECLARE @ID VARCHAR(3)
--查询ID = '001'的所有子节点
SET @ID = '007'
;WITH Temp AS (
SELECT id,pid,NAME FROM tb AS t WHERE t.id=@ID
UNION ALL
SELECT t2.id,t2.pid,t2.NAME FROM tb t2 INNER JOIN Temp tm on t2.pid=tm.ID
)
SELECT * FROM Temp AS t WHERE id!=@ID