如何在mssql查询中查找所有父项

时间:2018-03-19 12:40:19

标签: sql-server

CREATE TABLE foo (
    id int IDENTITY(1,1) PRIMARY KEY,
    parent_no int DEFAULT 0,
    name varchar(255)
);

INSERT INTO foo (name, parent_no) VALUES ('Locations', 0);
INSERT INTO foo (name, parent_no) VALUES ('NSW', 1);
INSERT INTO foo (name, parent_no) VALUES ('QLD', 1);
INSERT INTO foo (name, parent_no) VALUES ('VIC', 1);
INSERT INTO foo (name, parent_no) VALUES ('Sydney', 2);
INSERT INTO foo (name, parent_no) VALUES ('Brisbane', 3);
INSERT INTO foo (name, parent_no) VALUES ('Melbourne', 4);
INSERT INTO foo (name, parent_no) VALUES ('Sydney Head Office', 5);
INSERT INTO foo (name, parent_no) VALUES ('Brisbane Head Office', 6);
INSERT INTO foo (name, parent_no) VALUES ('Melbourne Head Office', 7);
INSERT INTO foo (name, parent_no) VALUES ('Level 21 Martin Place', 8);
INSERT INTO foo (name, parent_no) VALUES ('Level 22 Martin Place', 8);
INSERT INTO foo (name, parent_no) VALUES ('Level 23 Martin Place', 8);
INSERT INTO foo (name, parent_no) VALUES ('Level 24 Martin Place', 8);
INSERT INTO foo (name, parent_no) VALUES ('First Floor', 9);
INSERT INTO foo (name, parent_no) VALUES ('Ground Floor', 9);
INSERT INTO foo (name, parent_no) VALUES ('Second Floor', 9);

如果找到所有父母,如果id = 11 name =“Level 21 Martin Place”

sql fiddle

中的代码

0 个答案:

没有答案