在具有ParentID的表中选择HasChildren

时间:2013-09-03 05:46:50

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

我有下表,

CREATE TABLE [dbo].[Catalogs]
(
    [ID] [INT] IDENTITY(1,1) NOT NULL,
    [Name] NVARCHAR(255) NOT NULL,
    [Description] NVARCHAR(500) NULL,
    [Icon] NVARCHAR(255) NULL,
    [Order] INT NOT NULL,
    [ParentID] INT NULL,
    [CreatorID] INT NOT NULL,
    [LastModifierID] INT NOT NULL,
    [CreationDate] DATETIME NOT NULL,
    [LastModifiedDate] DATETIME NOT NULL,
    PRIMARY KEY (ID)
)

现在我想选择HasChildren列的所有目录。

编辑:HasChildren将在运行时生成。如果行的ID在所有行的ParentID列中都不可用。

4 个答案:

答案 0 :(得分:2)

SELECT *,
 CASE WHEN EXISTS (SELECT * FROM [dbo].[Catalogs] c WHERE c.ParentID = p.Id) 
      THEN 1 ELSE 0 END AS HasChildren
FROM [dbo].[Catalogs] p

答案 1 :(得分:1)

请尝试此查询:

SELECT * , 
        HasChildren = CASE WHEN(SELECT COUNT(*) FROM  [dbo].[Catalogs] as child WHERE parent.[ID]=child.[ParentID])>0 THEN 1 ELSE 0 END
        FROM [dbo].[Catalogs] as  parent

答案 2 :(得分:1)

SELECT * , 
CASE WHEN(SELECT COUNT(*) FROM  Table1 as child 
WHERE parent.[ID]=child.[ParentID])>0 THEN 1 ELSE 0 END
AS HasChildren
FROM Table1 as  parent

<强> FIDDLE

答案 3 :(得分:0)

假设一个具有层次结构的表,您想在其中查询层次结构中包含子项的行,您应该尝试这样的事情:

SELECT DISTINCT t1.* 
FROM   TABLE1 t1 
       INNER JOIN TABLE1 t2 
               ON t2.PARENTID = t1.ID 

查看SQL Fiddle上的工作示例。