命名类别和子类别表

时间:2014-07-04 09:30:36

标签: sql sql-server

我正在尝试在数据库中创建一堆查找表,但在命名它们时却被卡住了。表格如下:

 1. dbo.AccountType (this is the highest level category)
 2. dbo.AccountSubType (this is a 2nd level category)
 3. dbo.AccountSubSubType (this is a 3rd level category)

上述命名约定容易破解。所以也许这更好:

 1. dbo.AccountType1 (highest level)
 2. dbo.AccountType2 (second level)
 3. dbo.AccountType3 (third level)
 4. dbo.AccountType-N (and so on...)

我知道命名约定是基于意见的,但肯定必须有一些逻辑方法来实现这一点,这是可扩展的,而不是让开发人员感到困惑。

使用第二种解决方案在dbo.AccountType2表中查看数据的示例:

AccountTypeID (FK) | AccountType1ID (FK) | AccountType2ID (PK) | AccountType2
=============================================================================
1                    4                     1                     Credit Card
1                    5                     2                     Savings

有没有更好的方法在数据库中存储分层数据并正确命名表?

1 个答案:

答案 0 :(得分:2)

这可能更好地表示为具有层次关系的单个表:

E.g。

CREATE TABLE [dbo].[AccountType] (
    Id int NOT NULL
    ,ParentId int NULL
    CONSTRAINT [FK_AccountType_AccountType_Parent] REFERENCES [dbo].[AccountType] (Id)
    ,Name nvarchar(200) NOT NULL
    CONSTRAINT [PK_AccountType] PRIMARY KEY CLUSTERED ([Id])
)

然后用以下数据填充它:

INSERT INTO dbo.AccountType (Id, ParentId, Name) VALUES (1, NULL, 'Credit Card')
INSERT INTO dbo.AccountType (Id, ParentId, Name) VALUES (2, 1, 'Credit Card Sub-Type')
INSERT INTO dbo.AccountType (Id, ParentId, Name) VALUES (3, 2, 'Credit Card Sub-Sub-Type')

INSERT INTO dbo.AccountType (Id, ParentId, Name) VALUES (4, NULL, 'Savings')
INSERT INTO dbo.AccountType (Id, ParentId, Name) VALUES (5, 4, 'Savingsd Sub-Type')
INSERT INTO dbo.AccountType (Id, ParentId, Name) VALUES (6, 5, 'Savings Sub-Sub-Type')

ParentId NULL的任何内容都是根值,否则它是指定父级的子级...

修改:要查询您,请使用CTE。 E.g。

WITH ParentAccountType ( Id, ParentId, Name, ParentName )
AS
(
    SELECT Id, ParentId, Name, CAST('N/A' AS nvarchar(200)) AS ParentName
    FROM AccountType
    WHERE ParentId IS NULL
    UNION ALL
    SELECT c.Id, c.ParentId, c.Name, p.Name AS ParentName
    FROM
        AccountType c
        INNER JOIN ParentAccountType p ON c.ParentId = p.Id
)
SELECT ParentName, Name
FROM ParentAccountType
GO

SQL Fiddler here