3

基于这个答案

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

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

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

4

1 回答 1

3

这是因为您可以null将列作为值。并且 SQL 具有三值逻辑,因此检查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

于 2013-09-25T14:08:02.677 回答