用于从表中获取数据的SQL服务器逻辑

时间:2013-09-22 18:53:10

标签: sql-server tsql sql-server-2008-r2

“需要显示链接到父类别的所有项目id = 1根据表格,它应该获取:Big Machine,计算机,CPU机柜,硬盘和磁盘。但是根据写入的逻辑,它不是获取所有记录.Plz帮助..“

  create table ItemSpares
  (
        ItemName varchar(20),
        ItemID int,
        ParentCategoryID int
  )

  insert into ItemSpares (ItemName,ItemID,ParentCategoryID)
  select 'Big Machine', 1 , NULL UNION ALL
  select 'Computer', 2, 1 UNION ALL
  select 'CPU Cabinet', 3, 2 UNION ALL
  select 'Hard Disk', 4, 3 UNION ALL
  select 'Magnetic Disk',5,4 UNION ALL
  select 'Another Big Machine',6, NULL 

1 个答案:

答案 0 :(得分:0)

您需要使用分层SQL查询,需要一段时间才能弄明白,但请尝试以下方法:

with BigComputerList (ItemName, ItemID, ParentCategoryID, Level) 
AS
(
-- Anchor member definition
    SELECT e.ItemName, e.ItemID, e.ParentCategoryID,
        0 AS Level
    FROM ItemSpares AS e
    WHERE ItemID = 1
    UNION ALL
-- Recursive member definition
    SELECT e.ItemName, e.ItemID, e.ParentCategoryID,
        Level + 1
    FROM ItemSpares AS e    
    INNER JOIN BigComputerList AS d
        ON e.ParentCategoryId = d.ItemID
)

Select * From BigComputerList

如果您想了解查询正在做什么,我强烈建议您阅读此article