T-sql,查询父ID

时间:2016-07-29 08:53:09

标签: sql-server tsql

我有一张这样的表:

enter image description here

我想写一个这样的查询:如果我选择DictID,其中DictParentID为NULL(这意味着这是父ID),我想列出所有DictID与DictParentID =我的DictID(在本例中为10240)以及10240。 在其他情况下(当DictParentID不为NULL时我选择DictID)我想只列出这个DictID。

编写此查询时遇到问题。感谢

3 个答案:

答案 0 :(得分:1)

简单高效,使用UNION ALL

SELECT DictiId, DictParentId
FROM dbo.TableName t
WHERE DictId = @DictId

UNION ALL

SELECT DictiId, DictParentId
FROM dbo.TableName t
WHERE DictParentId = @DictId

如果您想订购,可以使用子查询:

SELECT x.DictiId, x.DictParentId FROM
(
    SELECT DictiId, DictParentId
    FROM dbo.TableName t
    WHERE DictId = @DictId

    UNION ALL

    SELECT DictiId, DictParentId
    FROM dbo.TableName t
    WHERE DictParentId = @DictId
) x
ORDER BY x.DictiId, x.DictParentId

答案 1 :(得分:0)

简单高效,使用SELECT DictiId, DictParentId FROM dbo.TableName t WHERE DictId = @DictId OR DictParentId = @DictId

<DataTemplate DataType="{x:Type viewModel:ActionItem}">

    <Button Background="SlateGray" Command="{Binding Command}">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="Background" Value="Green"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Background="{TemplateBinding Background}">
                                <ContentPresenter />
                            </Border>

                 <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="DarkGoldenrod"/>
                    </Trigger>
                </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Style>
        </Button.Style>

        <TextBlock Text="{Binding Name}" />

    </Button>

</DataTemplate>

答案 2 :(得分:0)

你可以将我们的好朋友in条款翻转到这里以获得良好效果:

SELECT DictiId, DictParentId
FROM dbo.TableName t
WHERE @DictId in (DictId, DictParentId);
相关问题