sql层次结构查询

时间:2017-12-12 08:14:14

标签: sql sql-server

我有一些表格如图所示,我想实现输出,如上表所示。是否可以使用带有SP的

的sql server查询来实现它

Diagram of table

BB

1 个答案:

答案 0 :(得分:0)

您可以按照以下方式执行此操作。我给了一些自由,因为你给的关系不是很清楚:

IF OBJECT_ID ('role') IS NOT NULL
    DROP TABLE role
GO

CREATE TABLE role
    (
    roid   INT NULL,
    roname VARCHAR (20) NULL
    )
GO

IF OBJECT_ID ('rolechild') IS NOT NULL
    DROP TABLE rolechild
GO

CREATE TABLE rolechild
    (
    parentroid INT NULL,
    childroid  INT NULL
    )
GO

IF OBJECT_ID ('rolechildrel') IS NOT NULL
    DROP TABLE rolechildrel
GO

CREATE TABLE rolechildrel
    (
    roid   INT NULL,
    rtroid INT NULL
    )
GO

IF OBJECT_ID ('rt') IS NOT NULL
    DROP TABLE rt
GO

CREATE TABLE rt
    (
    rtid   INT NULL,
    rtname VARCHAR (20) NULL
    )
GO

IF OBJECT_ID ('urore') IS NOT NULL
    DROP TABLE urore
GO

CREATE TABLE urore
    (
    uid  INT NULL,
    roid INT NULL
    )
GO

IF OBJECT_ID ('usern') IS NOT NULL
    DROP TABLE usern
GO

CREATE TABLE usern
    (
    uid   INT NULL,
    uname VARCHAR (20) NULL
    )
GO


SELECT u.uname,r.roname,rt.rtname
FROM
usern u JOIN urore ur ON (u.uid = ur.uid)
JOIN role r ON (ur.roid = r.roid)
JOIN rolechild rc ON (r.roid = rc.parentroid)
JOIN rolechildrel rcl ON (rc.childroid = rcl.roid)
JOIN rt ON rcl.rtroid = rt.rtid