-1

我有下表,

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

4 回答 4

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
于 2013-09-03T07:07:01.003 回答
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

小提琴

于 2013-09-03T07:15:09.577 回答
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
于 2013-09-03T05:54:42.290 回答
0

假设有一个层次结构的表,你想查询层次结构中有子行的行,你应该尝试这样的事情:

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

看一下SQL Fiddle上的一个工作示例。

于 2013-09-03T05:54:03.207 回答