SQL存储过程if(@variable = 0)不起作用

时间:2011-01-19 16:06:08

标签: sql sql-server stored-procedures

我创建了一个包含一些变量和嵌套if语句的存储过程。 当我从我的程序调用存储过程并检查返回的数据集中返回的值时,我的数据集是空的,同时应该有记录。经过一些测试,我注意到当语句if(@PoolID = 0)被测试而@PoolID为0时,它不会通过if语句...所以每当我在我的代码中将变量poolid设置为0时,我得到了来自else语句的结果......

有谁知道出了什么问题? THX

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Pool_select]

@PartnerCode nvarchar(8),
@GebrID int,
@PoolID int,
@Bevoegdheid int

AS

IF (@PoolID = 0)
BEGIN
    IF (@Bevoegdheid < 3)
    BEGIN
        SELECT
        p.*,
        pr.poolrecht
        FROM racpPool p, racpPoolrecht pr
        WHERE
        p.poolid = pr.poolid and
        p.PartnerCode = @PartnerCode and
        pr.poolrecht > 0 and
        p.actief = 1 and
        pr.GebrID = @GebrID
    END
    ELSE
    BEGIN   
        SELECT *
        FROM racpPool p
        WHERE standaardpool = 1
        and partnercode = @PartnerCode
    END     
END
ELSE
BEGIN
    IF (@Bevoegdheid < 3)
    BEGIN
        SELECT
        p.*,
        pr.poolrecht
        FROM racpPool p, racpPoolrecht pr
        WHERE 
        p.poolid = pr.poolid and
        p.PartnerCode = @PartnerCode and
        pr.poolrecht > 0 and
        p.actief = 1 and
        pr.GebrID = @GebrID and 
        p.PoolID = @PoolID
    END
    ELSE IF (@Bevoegdheid >= 3)
    BEGIN   
        SELECT *
        FROM racpPool p
        WHERE PoolID = @PoolID
    END 
END 

1 个答案:

答案 0 :(得分:0)

您可以将其重写为一个由4个部分组成的UNION ALL。

我也注意到你的条件并不全面,不确定这是否是故意的。

@PoolID = 0的第二个分支中,测试具体为@Bevoegdheid < 3@Bevoegdheid >= 3(而不是ELSE),如果@Bevoegdheid IS NULL

则不会执行任何操作

优化器只会运行符合标有&lt;&lt;&lt;&lt;

的条件的分支
ALTER PROCEDURE [dbo].[Pool_select]
@PartnerCode nvarchar(8),
@GebrID int,
@PoolID int,
@Bevoegdheid int
-- WITH RECOMPILE -- << may need this

AS

    SELECT
    p.*,
    pr.poolrecht
    FROM racpPool p, racpPoolrecht pr
    WHERE
    p.poolid = pr.poolid and
    p.PartnerCode = @PartnerCode and
    pr.poolrecht > 0 and
    p.actief = 1 and
    pr.GebrID = @GebrID
    AND @PoolID = 0 and @Bevoegdheid < 3   --- <<<
UNION ALL
    SELECT *, NULL
    FROM racpPool p
    WHERE standaardpool = 1
    and partnercode = @PartnerCode
    AND @PoolID = 0 and IsNull(@Bevoegdheid,4) >= 3 --- <<<
UNION ALL
    SELECT
    p.*,
    pr.poolrecht
    FROM racpPool p, racpPoolrecht pr
    WHERE 
    p.poolid = pr.poolid and
    p.PartnerCode = @PartnerCode and
    pr.poolrecht > 0 and
    p.actief = 1 and
    pr.GebrID = @GebrID and 
    p.PoolID = @PoolID
    AND Isnull(@PoolID,-1) <> 0 AND @Bevoegdheid < 3   --- <<<
UNION ALL
    SELECT *, NULL
    FROM racpPool p
    WHERE PoolID = @PoolID
    AND Isnull(@PoolID,-1) <> 0 AND @Bevoegdheid >= 3  --- <<<