通用选择不适用于位类型

时间:2013-09-25 14:03:59

标签: sql sql-server generics select stored-procedures

基于this answer

我试图在我的桌子上创建一个选择

ALTER PROCEDURE _Einrichtung_Select

    -- Parameters with default values
        @EinrichtungId      AS int          = NULL,
        @EinrichtungName    AS nvarchar(50) = NULL,
        @IsKueche           AS bit          = NULL,
        @RefEinrichtungId   AS int          = NULL,
        @RefSpeiseplantypId AS int          = NULL

AS

    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
        SET NOCOUNT ON;

    -- generic SELECT query
        SELECT  *
        FROM    Einrichtung
        WHERE   EinrichtungId       = ISNULL(@EinrichtungId,        EinrichtungId)
        AND     EinrichtungName     = ISNULL(@EinrichtungName,      EinrichtungName)
        AND     IsKueche            = ISNULL(@IsKueche,             IsKueche)
        AND     RefEinrichtungId    = ISNULL(@RefEinrichtungId,     RefEinrichtungId)
        AND     RefSpeiseplantypId  = ISNULL(@RefSpeiseplantypId,   RefSpeiseplantypId)

        ORDER BY EinrichtungName

    RETURN

但我遇到了类型example sqlfiddle的问题,就像你可以看到它应该返回4行但它只返回3所以我错过了什么?

1 个答案:

答案 0 :(得分:3)

这是因为您可以将null作为列的值。 SQL有three-value logic,因此检查null = null将返回UNKNOWN而不是TRUE(正如您所料)。 我认为这个查询可以帮到你:

select *
from myTable
where
    (@EinrichtungId is null or EinrichtungId = @EinrichtungId) and
    (@EinrichtungName is null or EinrichtungName = @EinrichtungName) and
    (@IsKueche is null or IsKueche = @IsKueche) and
    (@RefEinrichtungId is null or RefEinrichtungId = @RefEinrichtungId) and
    (@RefSpeiseplantypId is null or RefSpeiseplantypId = @RefSpeiseplantypId)

<强> sql fiddle demo