34,837
社区成员




数据库是sqlserver2012,以下是表t1的数据和字段:
表t1有两个商品的数据结构:
15499的数据结构:
15600的数据结构:
如果bs_product_id=15499,如何写sql语句,从t1表取出数据?显示数据如下:
如果 bs_product_id=15600,如何写sql语句,从t1表取出数据?显示数据如下:
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([bs_product_id] int,[parent_id] int,[grade] int,[id] int)
Insert #T
select 15499,NULL,1,23 union all
select 15500,23,2,24 union all
select 15503,23,2,25 union all
select 15501,24,3,26 union all
select 15502,24,3,27 union all
select 15600,NULL,1,28 union all
select 15601,28,2,29 union all
select 15602,28,2,30
Go
--测试数据结束
DECLARE @bs_product_id INT = 15499;--参数,传入不同的值
;WITH cte AS (
SELECT * FROM #T WHERE bs_product_id=@bs_product_id
UNION ALL
SELECT #T.* FROM #T JOIN cte ON cte.id=#T.parent_id
)
SELECT * FROM cte